Joao Carlos
Joao Carlos

Reputation: 797

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?

Upvotes: 3

Views: 6959

Answers (4)

khn Rzk
khn Rzk

Reputation: 1282

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");

Upvotes: 2

gorodezkiy
gorodezkiy

Reputation: 3419

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

Upvotes: 8

user3942918
user3942918

Reputation: 26375

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

Upvotes: 8

Kal Zekdor
Kal Zekdor

Reputation: 1224

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.

Upvotes: 6

Related Questions