在PHP中时间的奇偶校验中进行日期验证


Date validation within pariode of time in PHP

如何检查时间戳格式(exp.2014-10-02 13:31:53)的日期字符串是否在PHP中的特定时间段内。

例如:

  1. 每日时段:今天、明天、昨天、两天前,依此类推
  2. 周周期:本周、下周、上周、两周前,依此类推
  3. 每月周期:本月、下个月、上个月、两个月前,依此类推
  4. 年周期:今年、明年、去年、两年前,依此类推

我建议使用DateTime类(PHP 5.2+)并使用比较运算符。例如,将本月的if进行比较,如下所示;

$start = new DateTime("First day of this month 00:00:00");
$end = new DateTime("Last day of this month 23:59:59");
$datetotest = new DateTime("2014-10-02 13:31:53");
if($datetotest >= $start and $datetotest <= $end) {
// do stuff
}

如果你愿意,你甚至可以为每一个写一个函数。

function isInThisMonth(DateTime $date) {
     $start = new DateTime("First day of this month 00:00:00");
     $end = new DateTime("Last day of this month 23:59:59");
     return ($date >= $start and $date <= $end);
}
if(isInThisMonth($datetotest)) // do stuff

如果你看一下PHP:DateTime相对格式,它会让你了解可以用来获得"去年"或其他内容的有效DateTime的描述。

希望这能有所帮助。