Home  >  Article  >  Backend Development  >  PHP determines whether a certain day is before or after the specified date_PHP Tutorial

PHP determines whether a certain day is before or after the specified date_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:26887browse

There is such a requirement. The specified date is December 12th. I want to execute event A before December 12th and event B after that. How to judge whether today is before December 12th? Or after?

The procedure is as follows:

<?php
$year = 2010;
$month = 12;  // 月
$day = 12;  // 日
$timeoffset = 8; // 与格林尼治时间 GMT 的时差
list($thisyear, $thismonth, $thisday) = explode('-', date('Y-n-j', time() + $timeoffset * 3600));
if(($thismonth > $month) || ($thismonth == $month && $thisday > $day) || $thisyear > $year) {
	echo '已经过了';
} elseif ($thismonth == $month && $thisday == $day && $thisyear == $year) {
	echo '就是今天了';
} else {
	echo '还没到';
}
?>

Here is the annotated code:

//你还需要知道的另一个变量是年份,不过依你的意思应该是当年。
$timestamp = time();
$dateYear = date('Y', $timestamp);//当前年,依当前需要可以不需要比较,但有时也许会用到,比如你的记录不是当年要处理的
$dateMonth = date('n', $timestamp);//当前月份数字,没有前导零
$dateDay = date('j', $timestamp);//月份中的第几天,没有前导零
//剩下的就是比较了,比如你要比较的日期是 2007-03-01
$eventDate = '2007-03-01';
$eventDateArr = explode('-', $eventDate);
$eventYear = intval($eventDateArr[0]);
$eventMonth = intval($eventDateArr[1]);
$eventDay = intval($eventDateArr[2]);
//上面是年月日的拆分,根据实际情况可以调整,如果你直接可以得到就不需要这样取了。
//之后剩下的就是比较了,先比较年
if($dateYear == $eventYear) {
  //同年
  if($dateMonth == $eventMonth) {
    //同月
    if($dateDay == $eventDay) {
      //同一天,就是当前日期就是事件触发的日期
    } elseif($dateDay > $eventDay) {
      //事件已经过期了
    } else {
      //事件触发日期还没到
    }
  } else {
    //之前或之后,再需要详细判断可以在这里比较哪个月份大
  }
} else {
  //之前或之后,再需要详细判断可以在这里比较哪个年份大
}
//其实这种比较是最简单的逻辑判断,如果你在记录时间触发日期时记录的是 unix 时间戳,这里可以直接进行时间戳比较不过需要处理一下,因为时间戳是精确到秒的
//或者把你记录的日期及其后一天直接转化成 unix 时间戳,时分秒都用 0 ,和当前时间戳比较,细节判断就自己去分析吧,可用函数去查查手册里面 strtotime() ,时间相关函数参数很多,不过用过几次就熟悉了。

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752485.htmlTechArticleThere is such a requirement. The specified date is December 12th. I want to execute event A before December 12th. , to execute event B later, how to determine whether today is before or after December 12? The procedure is as follows...
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