php date less than another date

孤者浪人 提交于 2019-12-05 20:13:44

问题


given this kind of date object date("m/d/Y", strtotime($numerical." ".$day." of ".date("F")))

where it may give a mm/dd/yyyy day that is the "first Monday of August", for instance

how can I decide if this date is greater than, less than, or equal to today's date?

I need a now() method that works in this format and can be compared between date objects

I haven't tried date() < date() , yet. But I don't think that will work

any insight appreciated


回答1:


Compare the timestamps:

if (strtotime($numerical." ".$day." of ".date("F")) < time()) {
    // older
} else {
    // newer
}

This is possible as strtotime() returns the seconds since 1.1.1970 and time() too. And in PHP you can easily compare integers...




回答2:


I misunderstood your question at first. You're not using a date object in the comparison like you say, but rather a string representation of a date (created by date).

It's easy to compare almost any string representation of a date to the current time:

$now = time();
$date = '2015/03/12'; #could be (almost) any string date

if (strtotime($date) > $now) {
    #$date occurs in the future
} else {
    #$date occurs now or in the past
}

Comparing a date string to the current day is only a little more complicated. Here's one way to do it:

$today_start = strtotime('today');
$today_end = strtotime('tomorrow');
$date = '2015/03/12'; #could be (almost) any string date

$date_timestamp = strtotime($date);

if ($date_timestamp >= $today_end) {
    #$date occurs after today
} elseif ($date_timestamp < $today_start) {
    #$date occurs before today
} else {
    #$date occurs today
}

Rather than use time to get the current time down to the second, you calculate the timestamps for the two midnights that bookend today's date. Then you compare against those.

There are more clever ways of doing this (such as comparing the YYYY/MM/DD representations of the date and today), but this example builds nicely on the first.



来源:https://stackoverflow.com/questions/17329281/php-date-less-than-another-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!