3

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?

0

4 Answers 4

8

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
8

You can also use something like strtotime(date('Y-m-d H:00:00'))

1
  • Upvoted because simpler and easier to read than DateTime stuff.
    – Arthur
    Commented Mar 4, 2021 at 11:41
6

As far as I know, there's no way to get the timestamp of the beginning of an hour using a verbal description. Even "last hour" is only returning now() - 3600.

Your best bet is the following:

$iCurrentTimestamp = strtotime("now");
$iStartOfHour = $iCurrentTimestamp - ($iCurrentTimestamp % 3600);

Now modulus 3600 will return the seconds after the start of the hour, then just subtract from the current time.

1
  • Nice solution. Thx.
    – Oleg Popov
    Commented Sep 16, 2016 at 15:38
2

To get the start time of the day

$starttime = date("Y-m-d H:i:s",strtotime("midnight"));

to current time

$endtime = date("Y-m-d H:i:s");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.