PHP:如何处理不规则的日期,如FEB29提醒应用程序


PHP: How to deal with irregular dates like FEB 29 for reminder application?

假设您正在创建一个需要每月向您发送电子邮件的应用程序。日期开始日期为2012年2月29日。既然没有2013年2月29日,你明年该如何应对。同样,如果开始日期是JAN 31,则没有FEB 31或APR 31,依此类推…

只需使用DateTime类就可以了:

如果我想要日期1个月从29/2/2012:

$date = new DateTime('2012-02-29'); // "start date"
$date->add(new DateInterval('P1M')); //one month later
echo $date->format('Y-m-d') . "'n"; //2012-03-29

一年后:

$date = new DateTime('2012-02-29'); //start
$date->add(new DateInterval('P1Y')); //one year later
echo $date->format('Y-m-d') . "'n"; //2013-03-01 

使用它,你可以很容易地计算出你需要的任何日期间隔。

改为在月1日发送:)

在将日期保存到数据库之前,我会测试它。

Get last day of any other month
Enter any month/day/year to get the last day of that month 
$lastday = date('t',strtotime('3/1/2009'));
If you want to display the last day of this month on your website, do the following:
<?php
echo date('t',strtotime('today'));
?>

来源:http://www.johnboy.com/blog/find-the-last-day-of-the-month-with-php

当脚本运行时,如果实际日期是一个月的最后一天,请检查实际日期,并根据结果采取行动。