search
HomeBackend DevelopmentPHP TutorialTeach you how to make a simple php calendar_php skills

In a recent project, the data needed to be displayed in a calendar. There are many JS plug-ins on the Internet. Later, in order to have greater control, I decided to make a calendar display myself. As shown below:

1. Calculated data
1. Create a new Calendar class

2. Initialize the data in the two drop-down boxes, year and month

3. Initialize the year and month to be searched

4. Calculate the data information of each day in the calendar, including css and number of days

<&#63;php
 require_once 'calendar.php';
 $util = new Calendar();
 $years = array(2012, 2013, 2014, 2015, 2016);//年份选择自定义
 $months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);//月份数组
 //获取post的年份数据
 if(empty($_POST['ddlYear'])) {
  $year = date('Y');
 }else {
  $year = $_POST['ddlYear'];
 }
 //获取post的月份数据
 if(empty($_POST['ddlMonth'])) {
  $month = date('n');
 }else {
  $month = $_POST['ddlMonth'];
 }

 $calendar = $util->threshold($year, $month);//获取各个边界值
 $caculate = $util->caculate($calendar);//计算日历的天数与样式
 $draws = $util->draw($caculate);//画表格,设置table中的tr与td
&#63;>

2. HTML display
1. The background color of rest days is different, and the font color of days other than the current search year and month is also different

2. Initialize the year and month drop-down boxes in the div, and select the year and month currently to be searched

3. The data has been calculated and which td belongs to which tr. You can just print out the table

<div style="padding:20px">
  <select name="ddlYear">
  <&#63;php foreach($years as $data) {&#63;>
   <option value="<&#63;php echo $data&#63;>" <&#63;php if($year == $data) echo 'selected="selected"'&#63;>><&#63;php echo $data&#63;></option>
  <&#63;php }&#63;>
  </select>
  <select name="ddlMonth">
  <&#63;php foreach($months as $data) {&#63;>
   <option value="<&#63;php echo $data&#63;>" <&#63;php if($month == $data) echo 'selected="selected"'&#63;>><&#63;php echo $data&#63;></option>
  <&#63;php }&#63;>
  </select>
  <input type="submit" value="修改"/>
 </div>
 <table width="100%" cellspacing="0" class="table_calendar">
  <thead class="f14">
    <tr>
     <td width="16%">日</td>
     <td width="14%">一</td>
     <td width="14%">二</td>
     <td width="14%">三</td>
     <td width="14%">四</td>
     <td width="14%">五</td>
     <td width="14%">六</td>
    </tr>
  </thead>
  <tbody class="f14">
   <&#63;php foreach($draws as $draw) {&#63;>
    <tr>
    <&#63;php foreach($draw as $date) {&#63;>
     <td class="<&#63;php echo $date['tdclass']&#63;>">
      <p class="<&#63;php echo $date['pclass']&#63;>"><&#63;php echo $date['day']&#63;></p>
     </td>
    <&#63;php }&#63;> 
    </tr>
   <&#63;php }&#63;>
  </tbody>
 </table>

3. Calendar class
1. Threshold method, generates each boundary value of the calendar

 1) Calculate the total number of days in this month

2) Calculate the first day and last day of this month, and what day of the week each is

 3) Calculate the first date and the last date in the calendar

/**
  * @deprecated 生成日历的各个边界值
  * @param string $year
  * @param string $month
  * @return array
  */
 function threshold($year, $month) {
  $firstDay = mktime(0, 0, 0, $month, 1, $year);
  $lastDay = strtotime('+1 month -1 day', $firstDay);
  //取得天数 
  $days = date("t", $firstDay);
  //取得第一天是星期几
  $firstDayOfWeek = date("N", $firstDay);
  //获得最后一天是星期几
  $lastDayOfWeek = date('N', $lastDay);
  
  //上一个月最后一天
  $lastMonthDate = strtotime('-1 day', $firstDay);
  $lastMonthOfLastDay = date('d', $lastMonthDate);
  //下一个月第一天
  $nextMonthDate = strtotime('+1 day', $lastDay);
  $nextMonthOfFirstDay = strtotime('+1 day', $lastDay);
  
  //日历的第一个日期
  if($firstDayOfWeek == 7)
   $firstDate = $firstDay;
  else 
   $firstDate = strtotime('-'. $firstDayOfWeek .' day', $firstDay);
  //日历的最后一个日期
  if($lastDayOfWeek == 6)
   $lastDate = $lastDay;
  elseif($lastDayOfWeek == 7) 
   $lastDate = strtotime('+6 day', $lastDay);
  else
   $lastDate = strtotime('+'.(6-$lastDayOfWeek).' day', $lastDay);
  
  return array(
    'days' => $days, 
    'firstDayOfWeek' => $firstDayOfWeek, 
    'lastDayOfWeek' => $lastDayOfWeek,
    'lastMonthOfLastDay' => $lastMonthOfLastDay,
    'firstDate' => $firstDate,
    'lastDate' => $lastDate,
    'year' => $year,
    'month' => $month
  );
 }

2. caculate method, calculate the number of days and style of the calendar

1) Calculate the number of days in the last month. If the first day of the month is not a Sunday, you need to calculate it based on the last day of the last month

2) Traverse the number of days in this month, and if it is a rest day, add a special css style

3) Calculate the number of days in the next month, divided into three situations, Sunday, Saturday and working days

/**
  * @author Pwstrick
   * @param array $calendar 通过threshold方法计算后的数据
  * @deprecated 计算日历的天数与样式
  */
 function caculate($calendar) {
  $days = $calendar['days'];
  $firstDayOfWeek = $calendar['firstDayOfWeek'];//本月第一天的星期
  $lastDayOfWeek = $calendar['lastDayOfWeek'];//本月最后一天的星期
  $lastMonthOfLastDay = $calendar['lastMonthOfLastDay'];//上个月的最后一天
  $year = $calendar['year'];
  $month = $calendar['month'];
  
  $dates = array();
  if($firstDayOfWeek != 7) {
   $lastDays = array();
   $current = $lastMonthOfLastDay;//上个月的最后一天
   for ($i = 0; $i < $firstDayOfWeek; $i++) {
    array_push($lastDays, $current);//添加上一个月的日期天数
    $current--;
   }
   $lastDays = array_reverse($lastDays);//反序
   foreach ($lastDays as $index => $day) {
    array_push($dates, array('day' => $day, 'tdclass' => ($index ==0 &#63;'rest':''), 'pclass' => 'outter'));
   }
  }
  
  //本月日历信息
  for ($i = 1; $i <= $days; $i++) {
   $isRest = $this->_checkIsRest($year, $month, $i);
   //判断是否是休息天
   array_push($dates, array('day' => $i, 'tdclass' => ($isRest &#63;'rest':''), 'pclass' => ''));
  }
  
  //下月日历信息
  if($lastDayOfWeek == 7) {//最后一天是星期日
   $length = 6;
  }
  elseif($lastDayOfWeek == 6) {//最后一天是星期六
   $length = 0;
  }else {
   $length = 6 - $lastDayOfWeek;
  }
  for ($i = 1; $i <= $length; $i++) {
   array_push($dates, array('day' => $i, 'tdclass' => ($i==$length &#63;'rest':''), 'pclass' => 'outter'));
  }
  
  return $dates;
 }

3. Draw method, draw the table, set tr and td in the table

1) The data will be displayed using table tags, so the td under each tr must be arranged

 2)$index % 7 == 0 Calculate the first column of each row of the table

 3)$index % 7 == 6 || $index == ($length-1) Calculate the last column of each row, or the last data of $caculate

 4) Add the middle row to $tr, which is the array of each row

 /**
  * @author Pwstrick
  * @param array $caculate 通过caculate方法计算后的数据
  * @deprecated 画表格,设置table中的tr与td
  */
 function draw($caculate) {
  $tr = array();
  $length = count($caculate);
  $result = array();
  foreach ($caculate as $index => $date) {
   if($index % 7 == 0) {//第一列
    $tr = array($date);
   }elseif($index % 7 == 6 || $index == ($length-1)) {
    array_push($tr, $date);
    array_push($result, $tr);//添加到返回的数据中
    $tr = array();//清空数组列表
   }else {
    array_push($tr, $date);
   }
  }
  return $result;
 }

Through this article, you should know how to make a calendar, so strike while the iron is hot and make a calendar of your own.

Source code attached: Teach you how to make a simple php calendar

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software