简体   繁体   中英

Getting Yesterdays Date at Exactly Midnight in PHP

Should I have any issue with this?

I am setting up a cron job at EXACTLY midnight

0   0   *   *   *    /usr/bin/php    myscript.php

The script is set to define the previous day's date in MySQL timestamp format.

$midnightyesterday2 = (new DateTime())->setTime(0, 0);
$midnightyesterday2->modify('-1 day');
$midnightyesterday = $midnightyesterday2->format("Y-m-d H:i:s");

echo output:

2017-04-08 00:00:00

$endofdayyesterday2 = (new DateTime())->setTime(23, 59, 59);
$endofdayyesterday2->modify('-1 day');
$endofdayyesterday = $endofdayyesterday2->format("Y-m-d H:i:s");

echo output:

2017-04-08 23:59:59

Obviously this sample output is working properly because I'm doing this at 15:22:00.

Is it just paranoia in me thinking setting up a cron job at midnight could cause conflict even by a half a second if the script is for some reason run a tad fraction early.

Is there a better way to ensure yesterdays date with a script set to run at exactly midnight?

I need it to run at exactly midnight because the script is based off a MySQL lastmodified timestamp as my echo suggests, and even running it at 12:01 could leave some behind of additional rows are added in that minute.

Please try the below code to get the yesterday's beginning and end date with exact hours.

date("Y-m-d H:i:s", strtotime("yesterday")); // 2018-09-18 00:00:00

date("Y-m-d H:i:s", strtotime("today 1 sec ago")); // 2018-09-18 23:59:59

My solution (that kind of came to me in the comments) was to do the following:

Remember, the script is set to run at exactly midnight (00:00:00).

So I'm setting up a new DateTime object, adding 12 hours. (12:00:00)

Then after moving it 12 hours ahead, using setTime to set the time to 00:00:00.

Then using DateTime's modify again to subtract 24 hours.

$midnightyesterday2 = new DateTime();
$midnightyesterday2->modify('+12 hour');
$midnightyesterday2->setTime(0, 0);
$midnightyesterday2->modify('-24 hour');
$midnightyesterday = $midnightyesterday2->format("Y-m-d H:i:s");
echo $midnightyesterday;

2017-04-08 00:00:00

Same with to get the end of day yesterday result

$endofdayyesterday2 = new DateTime();
$endofdayyesterday2->modify('+12 hour');
$endofdayyesterday2->setTime(23, 59, 59);
$endofdayyesterday2->modify('-24 hour');
$endofdayyesterday = $endofdayyesterday2->format("Y-m-d H:i:s");
echo $endofdayyesterday;

2017-04-08 23:59:59

I'm not saying this is the best way to do this, this idea just kind of came to me. But it seems to maybe add a kind of fail safe to what I'm trying to do.

I'll leave this open for a while if someone has a better or more proper solution.

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