简体   繁体   中英

How to check if a date is between other dates?

I get two dates from GET

$start = $_GET['start']; 
$end = $_GET['end'];

I then convert them into dates:

$start  = \DateTime::createFromFormat('d-m-yy', $start);
$end  = \DateTime::createFromFormat('d-m-yy', $end);

If I var_dump them I get

object(DateTime)#8260 (3) { ["date"]=> string(26) "2019-02-01 18:05:42.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } 
object(DateTime)#7967 (3) { ["date"]=> string(26) "2019-02-05 18:05:42.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

I then loop my posts and in a custom field I have a date, which is a string, therefore I convert it into a date:

foreach($posts as $post) { 
   $myDate = \DateTime::createFromFormat('d-m-yy', usp_get_meta(false,'usp-custom-80'));

And if I vur_dump that I get

object(DateTime)#8457 (3) { ["date"]=> string(26) "2000-03-20 18:07:28.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } 

Then I finally do:

if ( ( $myDate >= $start) && ( $myDate <= $end) ) {
....

But I don't get the correct results as if that conditions isn't working at all

您可以尝试:

if ( ( $myDate->getTimestamp() >= $start->getTimestamp()) && ( $myDate->getTimestamp() <= $end->getTimestamp()) )

You can compare seconds from Unix epoch start.

if ( ($start->format('U') <= $myDate->format('U')) 
    && ( $myDate->format('U') <= $end->format('U'))) {
    // date is between start and end
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM