我怎样才能获得前一个'早上4点'的时间?

I would like to get the time in seconds (standard time() format) of the previous '4 am'.

My first attempt was: mktime(4,0,0).

This works for every time of the day, except between 00:00 and 04:00, because than it will give the time of the next '4 am'.

  • So how do I tackle this problem?
$now    = new DateTime();
$fourAm = new DateTime('today 4am');

if ($now < $fourAm) {
    $time = strtotime('yesterday 4am');
} else {
    $time = $fourAm->getTimestamp();
}

Where $time is the timestamp of the "last 4am", regardless of what time it currently is.

Edit:

You could also do this without the DateTime objects, but I love that suite of classes, so I usually find any reason at all to use them. :-P

$now    = time();
$fourAm = strtotime('today 4am');

if ($now < $fourAm) {
    $time = strtotime('yesterday 4am');
} else {
    $time = $fourAm;
}
$date = strtotime('yesterday 4am');

If the time you have created is in the future, subtract one day.