search

Home  >  Q&A  >  body text

html - PHP如何生成一个指定年份一整年的日历

我想用php生成一段日历的html代码,而且这个日历是可以指定年份自动生成的,网上的代码都过于臃肿,要不就是搞了一个Class来生成,要不就是有一些我不要的功能。

请问有没有精简一点的方法来生成我要的日历呢,就像下面这种

伊谢尔伦伊谢尔伦2896 days ago716

reply all(4)I'll reply

  • P粉277518212

    P粉2775182122022-11-21 15:09:03

    Have you solved it, bro?

    reply
    0
  • PHPz

    PHPz2017-04-10 13:13:50

    <?php
      $year = '2013';
      $months =  array( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' );
      $days = array( 31, 
                     (strtotime("1 Mar ".$year) - strtotime("1 Feb ".$year)) / ( 24 * 60 * 60 ),
                     31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
      $wday = array( '', '', '', '', '', '', '' );
      $cal = array();
      foreach(range(0, 11) as $i) {
        $firstday = getdate(strtotime('1 '.$months[$i].' '.$year));
        $fromday = $firstday['wday'];
        $leftday =  7 - ( $fromday + $days[$i] ) % 7;
        $cal[] = array_merge( array_slice($wday, 0, $fromday),
                              range(1, $days[$i]),
                              array_slice($wday, 0, $leftday)
                            );
      }
    ?>
    <?php foreach(range(0, 11) as $i) : ?>
    <table>
      <thead>
        <tr><th colspan="7"><?php echo $months[$i].' '.$year; ?></th></tr>
        <tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th>
      </thead>
      <tbody>
        <tr>
        <?php
        foreach($cal[$i] as $k => $v) {
          if($k && !($k % 7)) echo "</tr><tr>";
          echo "<td>{$v}</td>";
        }
        ?>
        </tr>
      </tbody>
    </table>
    <?php endforeach ?>

    reply
    0
  • 阿神

    阿神2017-04-10 13:13:50

    从你的描述看来,只需要知道指定年份的每个月的天数和每天对应的周次即可。
    PHP中 Calendar 函数可以实现第一步:

    http://php.net/manual/zh/function.cal...
    int cal_days_in_month ( int $calendar , int $month , int $year )

    http://php.net/manual/zh/function.jdd...
    mixed jddayofweek ( int $julianday [, int $mode = CAL_DOW_DAYNO ] )

    剩下的就是写循环遍历所有月,按月生成日历了。

    reply
    0
  • 怪我咯

    怪我咯2017-04-10 13:13:50

        $begin = new DateTime( '2016-01-01' );
        $end = (new DateTime( '2016-12-31' ))->modify( '+1 day' );
    
        $interval = new DateInterval('P1D');
        $daterange = new DatePeriod($begin, $interval ,$end);
    
        foreach($daterange as $date){
            echo $date->format("Y-m-d"). "\n";
        }

    reply
    0
  • Cancelreply