如何检查当前日期/时间是否超过设定日期/时间?
检查PHP的strtotime
功能全到你设定的日期/时间转换为时间戳:http://php.net/manual/en/function.strtotime.php
如果strtotime
不能正确处理您的日期/时间格式(“4:00 PM”可能会工作,但不会“在4PM“),你需要使用字符串函数,例如substr
解析/更正您的格式并通过另一个函数(例如, mktime
。
然后将得到的时间戳与当前日期/时间(if ($calulated_timestamp > time()) { /* date in the future */ }
)进行比较,以查看设置的日期/时间是过去还是未来。
我建议阅读日期/时间函数上的PHP文档,并在您遇到困难时返回一些源代码。
由于PHP> = 5.2.0可以使用DateTime
类作为这样:
if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
# current time is greater than 2010-05-15 16:00:00 and thus in the past
}
传递给DateTime constructor的字符串进行解析according to these rules。
注意的是,还可以使用time
和strtotime
功能。 See original answer。
时间戳有一定的局限性交配,一些bug太多,例如时间戳无法在1970年之前办理的日期并在2038年后(见伊瓦尔科斯特的回答) – 2014-08-02 08:52:20
真棒的答案! :) – 2014-12-04 12:32:56
如果您使用的是UTC日期(如您应该那样),我们经常会看到滥用新的DateTime()而不使用参数,更喜欢使用新的DateTime(“now”,new DateTimeZone('UTC'))。这将防止您的应用程序在日期中误解错误。我建议你将它存储在一个函数的静态变量,一个类的静态或在你的运行过程中的其他地方... – Loenix 2016-10-12 08:01:10
还有DateTime类,它为比较运算符实现了一个函数。
// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');
if ($dtA > $dtB) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}
它实现的功能是什么? – 2017-09-02 03:57:16
dateTime对象范围从过去大约2920亿年到未来相同。时间戳功能有一个限制(如果我没有记错,从1970年开始到2038年)。
我有这个日期进行比较的,需要一些调整问题
function getDatetimeNow() {
$tz_object = new DateTimeZone('Europe/Belgrade');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
return $datetime->format('Y\-m\-d\ h:i:s');
}
$currentDate = getDatetimeNow();
$dtA = new DateTime($currentDate);
$dtB = new DateTime($date);
if ($dtA > $dtB) {
$active = 0;
return $active;
}
else {
$active = 1;
return $active;
}
看到伊瓦尔·科斯特的回答 – 2014-08-02 08:53:48