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's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor