Get timestamp of today and yesterday in php

How can I get the timestamp of 12 o'clock of today, yesterday and the day before yesterday by using strtotime() function in php?

12 o'clock is a variable and would be changed by user.


Solution 1:

$hour = 12;

$today              = strtotime($hour . ':00:00');
$yesterday          = strtotime('-1 day', $today);
$dayBeforeYesterday = strtotime('-1 day', $yesterday);

Solution 2:

strtotime supports a number of interesting modifiers that can be used:

$hour = 12;

$today              = strtotime("today $hour:00");
$yesterday          = strtotime("yesterday $hour:00");
$dayBeforeYesterday = strtotime("yesterday -1 day $hour:00");

echo date("Y-m-d H:i:s\n", $today);
echo date("Y-m-d H:i:s\n", $yesterday);
echo date("Y-m-d H:i:s\n", $dayBeforeYesterday);

It works as predicted:

2011-01-24 12:00:00
2011-01-23 12:00:00
2011-01-22 12:00:00