简体   繁体   中英

Comparing dates in wordpress

I am using following code in WordPress to check if articles are posted before 15-09-17 but the problem is if the date is greater than 15 and month is less it still shows the day is greater. For example if $pdate is 28-08-17 and $mydate is 15-09-17 it still return as true.

    $pdate  = strtotime(get_the_date("d-m-y"));
    $mydate =   strtotime('15-09-17');
    if ($pdate>$mydate)
    {
    //do something
    }
    else {
    //do something
    }

It's interpreting your first numbers (ie 28 and 15) as the year.

From the strtotime() manual:

If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as ymd.

Try using a four digit year so it doesn't parse the date string in an undesirable way:

$pdate  = strtotime(get_the_date("d-m-Y"));
$mydate =   strtotime('15-09-2017');
if ($pdate>$mydate)
{
//do something
}
else {
//do something
}

You've specified the format of $pdate using dmy ; however, $mydate follows the format set in Settings > General . Make sure the two formats match to have correct comparison.

To clarify, let the code reflect the date format in your setting. Say you want the date in your posts to appear like so: September 20, 2017 , which is F j, Y . Your code will be:

$pdate  = strtotime(get_the_date('F j, Y'));
    $mydate =   strtotime('September 15, 2017');
    if ($pdate>$mydate)
    {
    //do something
    }
    else {
    //do something
    }

With the new update the code that works is as follows:

<?php 

$pdate  = get_post_timestamp();
$mydate = time();
if ($pdate < $mydate) {
    echo 'Do something';
} else {
    echo 'Do something else';
}

More info at Wordpress 5.3 - Date/Time Improvements

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