最近工作中用到的一个并没有卵用的功能,根据开始日期和结束日期,生成日历数组
php的部分如下
function build_calendar($start,$end) {
$start_month = (Int)date('m',strtotime($start));
$start_year = (Int)date('Y',strtotime($start));
$end_year = (Int)date('Y',strtotime($end));
$end_month = (Int)date('m',strtotime($end));
if ( $start_month == 1 ) {
$month = 12;
$year = $start_year - 1;
}else{
$month = $start_month - 1;
$year = $start_year;
}
$results = [];
while ( !($year == $end_year && $month == $end_month) ) {
if ( $month == 12 ) {
$year++;
$month = 1;
}else{
$month++;
}
// 本月第一天的位置
$firstDayOfMonth = mktime(0,0,0,$month,1,$year);
// 获取本月天数
$numberDays = date('t',$firstDayOfMonth);
// 获取本月第一天
$dateComponents = getdate($firstDayOfMonth);
$dayOfWeek = $dateComponents['wday'];
// 初始化天数计数器,从1号开始
$n = 0;
$result = [];
$line = 0;
while ($n < $numberDays) {
// 7天一行,7天一到新增一行
if ($dayOfWeek == 7) {
$dayOfWeek = 0;
}
$result[$line][$dayOfWeek] = date('Y-m-d',strtotime('+ '.$n.'days',$firstDayOfMonth));
if ( $dayOfWeek == 6 ) {
$line++;
}
// 计数器
$n++;
$dayOfWeek++;
}
$showMonth = str_pad($month, 2, "0", STR_PAD_LEFT);
$results[$year.'-'.$showMonth] = $result;
}
return $results;
}
传入开始日期及结束日期,生成月历如下
{
"2017-10": [
[
"2017-10-01",
"2017-10-02",
"2017-10-03",
"2017-10-04",
"2017-10-05",
"2017-10-06",
"2017-10-07"
],
[
"2017-10-08",
"2017-10-09",
"2017-10-10",
"2017-10-11",
"2017-10-12",
"2017-10-13",
"2017-10-14"
],
[
"2017-10-15",
"2017-10-16",
"2017-10-17",
"2017-10-18",
"2017-10-19",
"2017-10-20",
"2017-10-21"
],
[
"2017-10-22",
"2017-10-23",
"2017-10-24",
"2017-10-25",
"2017-10-26",
"2017-10-27",
"2017-10-28"
],
[
"2017-10-29",
"2017-10-30",
"2017-10-31"
]
],
"2017-11": [
{
"3": "2017-11-01",
"4": "2017-11-02",
"5": "2017-11-03",
"6": "2017-11-04"
},
[
"2017-11-05",
"2017-11-06",
"2017-11-07",
"2017-11-08",
"2017-11-09",
"2017-11-10",
"2017-11-11"
],
[
"2017-11-12",
"2017-11-13",
"2017-11-14",
"2017-11-15",
"2017-11-16",
"2017-11-17",
"2017-11-18"
],
[
"2017-11-19",
"2017-11-20",
"2017-11-21",
"2017-11-22",
"2017-11-23",
"2017-11-24",
"2017-11-25"
],
[
"2017-11-26",
"2017-11-27",
"2017-11-28",
"2017-11-29",
"2017-11-30"
]
]
}
网友评论