欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP简单创建日历的方法

程序员文章站 2023-12-20 09:36:16
本文实例讲述了php简单创建日历的方法。分享给大家供大家参考,具体如下:

本文实例讲述了php简单创建日历的方法。分享给大家供大家参考,具体如下:

<?php
function build_calendar($month,$year) {
  // create array containing abbreviations of days of week.
  $daysofweek = array('s','m','t','w','t','f','s');
  // what is the first day of the month in question?
  $firstdayofmonth = mktime(0,0,0,$month,1,$year);
  // how many days does this month contain?
  $numberdays = date('t',$firstdayofmonth);
  // retrieve some information about the first day of the
  // month in question.
  $datecomponents = getdate($firstdayofmonth);
  // what is the name of the month in question?
  $monthname = $datecomponents['month'];
  // what is the index value (0-6) of the first day of the
  // month in question.
  $dayofweek = $datecomponents['wday'];
  // create the table tag opener and day headers
  $calendar = "<table class='calendar'>";
  $calendar .= "<caption>$monthname $year</caption>";
  $calendar .= "<tr>";
  // create the calendar headers
  foreach($daysofweek as $day) {
     $calendar .= "<th class='header'>$day</th>";
  }
  // create the rest of the calendar
  // initiate the day counter, starting with the 1st.
  $currentday = 1;
  $calendar .= "</tr><tr>";
  // the variable $dayofweek is used to
  // ensure that the calendar
  // display consists of exactly 7 columns.
  if ($dayofweek > 0) {
     $calendar .= "<td colspan='$dayofweek'> </td>";
  }
  $month = str_pad($month, 2, "0", str_pad_left);
  while ($currentday <= $numberdays) {
     // seventh column (saturday) reached. start a new row.
     if ($dayofweek == 7) {
       $dayofweek = 0;
       $calendar .= "</tr><tr>";
     }
     $currentdayrel = str_pad($currentday, 2, "0", str_pad_left);
     $date = "$year-$month-$currentdayrel";
     $calendar .= "<td class='day' rel='$date'>$currentday</td>";
     // increment counters
     $currentday++;
     $dayofweek++;
  }
  // complete the row of the last week in month, if necessary
  if ($dayofweek != 7) {
     $remainingdays = 7 - $dayofweek;
     $calendar .= "<td colspan='$remainingdays'> </td>";
  }
  $calendar .= "</tr>";
  $calendar .= "</table>";
  return $calendar;
}
//调用方法
echo build_calendar(05,2016);
?>

运行结果如下图所示:

PHP简单创建日历的方法

关于在线显示日期还可参考本站在线工具:




更多关于php相关内容感兴趣的读者可查看本站专题:《php日期与时间用法总结》、《php数学运算技巧总结》、《php数组(array)操作技巧大全》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家php程序设计有所帮助。

上一篇:

下一篇: