1 <?php
2 //1.初始化年月信息 最后返回年、月、月中天数、 月中1号是星期几
3 function construct(){
4 //初始化年月
5 $year = isset($_GET['year'])?$_GET['year']:date('Y');
6 $month = isset($_GET['month'])?$_GET['month']:date('m');
7 //获取对应年份中月有多少天
8 $day = date('t',mktime(0,0,0,$month,1,$year));
9 //获取对应年份中月的1号是星期几
10 $w = date('w',mktime(0,0,0,$month,1,$year));
11 return $year.','.$month.','.$day.','.$w;
12 //2017,09,30,5
13 }
14 //2.根据上面的函数返回信息 遍历万年历表格
15 function myshow(){
16 //需要年月以及月份中天数和月份中1号是星期几
17 $result = construct();
18 //将获取到的字符串分割成数组
19 list($year,$month,$day,$w) = explode(',',$result);
20 echo '<table border="1" align="center" width="800">';
21 echo '<caption>'.$year.'年'.$month.'</caption>';
22 echo '<tr>';
23 echo '<th>星期日</th>';
24 echo '<th>星期一</th>';
25 echo '<th>星期二</th>';
26 echo '<th>星期三</th>';
27 echo '<th>星期四</th>';
28 echo '<th>星期五</th>';
29 echo '<th>星期六</th>';
30 echo '</tr>';
31 $num = 1;
32 while($num <= $day){
33 echo '<tr>';
34 for ($i=0; $i < 7; $i++) {
35 if($num>$day || ($w>$i && $num ==1)){
36 echo '<td> </td>';
37 }else{
38 echo '<td>'.$num.'</td>';
39 $num ++;
40 }
41 }
42 echo '</tr>';
43 }
44 echo '<tr>';
45 echo '<td colspan="7" align="center">'.chageDate($year,$month).'</td>';
46 echo '</tr>';
47
48 }
49 myshow();
50 //
51 //3.显示上一年、上一月、下一年、下一月 效果
52 function chageDate($year,$month){
53 $out = '<a href="?'.preYear($year,$month).'">《上一年</a> ';
54 $out .= '<a href="?'.preMonth($year,$month).'">《《上一月</a> ';
55 $out .= '<a href="?'.nextMonth($year,$month).'">下一月》》</a> ';
56 $out .= '<a href="?'.nextYear($year,$month).'">下一年》</a>';
57 return $out;
58 }
59
60 //echo chageDate();
61 //4.判断处理上一年函数 当前年-1 月份保持不变
62 function preYear($year,$month){
63 $year -= 1;
64 if($year < 1970){
65 $year = 1970;
66 }
67 return "year={$year}&month={$month}";
68 }
69 //
70 //5.判断上一月
71 function preMonth($year,$month){
72 //月份判断
73 if($month == 1){
74 $year -= 1;
75 //最小年的验证
76 if($year < 1970){
77 $year = 1970;
78 $month = 1;
79 }else{
80 $month = 12;
81 }
82 }else{
83 $month --;
84 }
85 return "year={$year}&month={$month}";
86 }
87 //6.判断下一月
88 function nextMonth($year,$month){
89 if($month == 12){
90 $year ++;
91 $month = 1;
92 }else{
93 //最大年时月份只能为1月
94 if($year == 2038){
95 $month =1;
96 }else{
97 $month ++;
98 }
99 }
100 return "year={$year}&month={$month}";
101 }
102 //7.判断下一年
103 function nextYear($year,$month){
104 $year ++;
105 //验证最大年
106 if($year >= 2038){
107 $year = 2038;
108 $month = 1;
109 }
110 return "year={$year}&month={$month}";
111 }