php calender(日历)二个版本代码示例(解决2038问题(2)


<?php
/**
 *
 * 我的日历(DateTime版本)
 * date_default_timezone_set date mktime
 * @param int $year
 * @param int $month
 * @param string $timezone
 * @author fc_lamp
 * @blog: fc-lamp.blog.163.com
 */
function myCalender($year = '', $month = '', $timezone = 'Asia/Shanghai')
{

 date_default_timezone_set ( $timezone );
 $year = abs ( intval ( $year ) );
 $month = abs ( intval ( $month ) );

 $nowDate = new DateTime();

 if ($year <= 0)
 {
  $year = $nowDate->format( 'Y' );
 }

 if ($month <= 0 or $month > 12)
 {
  $month = $nowDate->format('m' );
 }

 //上一年
 $pretYear = $year - 1;
 //上一月
 $mpYear = $year;
 $preMonth = $month - 1;
 if ($preMonth <= 0)
 {
  $preMonth = 1;
  $mpYear = $pretYear;
 }

 //下一年
 $nextYear = $year + 1;
 //下一月
 $mnYear = $year;
 $nextMonth = $month + 1;
 if ($nextMonth > 12)
 {
  $nextMonth = 1;
  $mnYear = $nextYear;
 }

 //日历头
 $html = <<<HTML
<table>
  <tr>
    <td><a href="https://www.jb51.net/?y=$pretYear">上一年</a></td>
    <td><a href="https://www.jb51.net/?y=$mpYear&m=$preMonth">上一月</a></td>
     <td><a href="https://www.jb51.net/article/?">回到今天</a></td>
    <td><a href="https://www.jb51.net/?y=$mnYear&m=$nextMonth">下一月</a></td>
 <td><a href="https://www.jb51.net/?y=$nextYear">下一年</a></td>
  </tr>
  <tr>
    <td colspan="5">{$year}年{$month}月</td>
  </tr>
  <tr>
   <td colspan="5">
  <table>
   <tr>
    <td>星期一</td>
    <td>星期二</td>
    <td>星期三</td>
    <td>星期四</td>
    <td>星期五</td>
    <td>星期六</td>
    <td>星期天</td>
   </tr>
HTML;

 $currentDay = $nowDate->format('Y-m-j' );

 //当月最后一天
 $creatDate = new DateTime("$year-$nextMonth-0");
 $lastday = $creatDate->format('j');
 $creatDate = NULL;

 //循环输出天数
 $day = 1;
 $line = '';
 while ( $day <= $lastday )
 {
  $cday = $year . '-' . $month . '-' . $day;

  //当前星期几
  $creatDate = new DateTime("$year-$month-$day");
  $nowWeek = $creatDate->format('N');
  $creatDate = NULL;

  if ($day == 1)
  {
   $line = '<tr>';
   $line .= str_repeat ( '<td>&nbsp;</td>', $nowWeek - 1 );
  }

  if ($cday == $currentDay)
  {
   $style = 'style="color:red;"';
  } else
  {
   $style = '';
  }

  $line .= "<td $style>$day</td>";

  //一周结束
  if ($nowWeek == 7)
  {
   $line .= '</tr>';
   $html .= $line;
   $line = '<tr>';
  }

  //全月结束
  if ($day == $lastday)
  {
   if ($nowWeek != 7)
   {
    $line .= str_repeat ( '<td>&nbsp;</td>', 7 - $nowWeek );
   }
   $line .= '</tr>';
   $html .= $line;

   break;
  }

  $day ++;
 }

 $html .= <<<HTML
  </table> 
 </td>
  </tr>
</table>
HTML;
 return $html;
}

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/54eec2e90d8eec0f176ad5ce34580ccc.html