Skip to content
Advertisement

strtotime to get first start of this hour

I am using strtotime("first day of this month", time()); to get the start of the current month, strtotime("midnight", time()); to get the start of the current day. Now I want to get the start of the current hour.

strtotime("last hour", time()); gives me the current hour, minus 1.

Looking at the docs, I see that you can build expressions to get the times you want, however, I have tried several and I am stuck. “First sec of this hour” or “first second of this hour” and “this hour” (same as “now”) all give me incorrect values.

How would I go about getting the timestamp of the first moment of the current hour using strtotime?

Advertisement

Answer

I’d use DateTime instead. You can still work with the same formats as strtotime, but it also gives you an interface to do things strtotime can’t.

Example:

$date = new DateTime(); // Defaults to now.
$date->setTime($date->format('G'), 0); // Current hour, 0 minute, [0 second]
echo $date->format(DateTime::RFC850), "n";
echo $date->getTimestamp();

Output:

Tuesday, 13-Oct-15 02:00:00 UTC
1444701600
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement