开发者

Get timestamp of today and yesterday in php

开发者 https://www.devze.com 2023-02-06 21:53 出处:网络
How can I get the timestamp of 12 o\'clock of today, yesterday and t开发者_JAVA技巧he day before yesterday by using strtotime() function in php?

How can I get the timestamp of 12 o'clock of today, yesterday and t开发者_JAVA技巧he day before yesterday by using strtotime() function in php?

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


$hour = 12;

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


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


OO Equivalent

$iHour = 12;

$oToday = new DateTime();
$oToday->setTime($iHour, 0);

$oYesterday = clone $oToday;
$oYesterday->modify('-1 day');

$oDayBefore = clone $oYesterday;
$oDayBefore->modify('-1 day');

$iToday     = $oToday->getTimestamp();
$iYesterday = $oYesterday->getTimestamp();
$iDayBefore = $oDayBefore->getTimestamp();

echo "Today: $iToday\n";
echo "Yesterday: $iYesterday\n";
echo "Day Before: $iDayBefore\n";


You can easily find out any date using DateTime object, It is so flexible

$yesterday = new DateTime('yesterday');
echo $yesterday->format('Y-m-d');

$firstModayOfApril = new DateTime('first monday of april');
echo $firstModayOfApril->format('Y-m-d');

$nextMonday = new DateTime('next monday');
echo $nextMonday->format('Y-m-d');


to get start of day yesterday

$oDate = new DateTime(); 
$oDate->modify('-1 day'); 
echo $oDate->format('Y-m-d 00:00:00');

result

2014-11-05 00:00:00


All the answers here are too long and bloated, everyone loves one-lines ;)

$yesterday = Date('Y-m-d', strtotime('-1 day'));

(Or if you are American you can randomize the date unit order to m/d/y (or whatever you use) and use Cups, galloons, feet and horses as units...)


As of PHP 7 you can write something like this:

$today = new \DateTime();
$yesterday = (clone $today)->modify('-1 day');
$dayBefore = (clone $yesterday)->modify('-1 day');
// Then call ->format('Y-m-d 00:00:00'); on each objects


you can also use new DateTime("now") for today new DateTime("1 day ago") for yesterday or all can be parse by strtotime php function.

Then format as you want.


$timeStamp = time();
// $timeStamp = time() - 86400;

if (date('d.m.Y', $timeStamp) == date('d.m.Y')) {    
  echo 'Today'; 
} elseif (date('d.m.Y', $time) == date('d.m.Y', strtotime('-1 day'))) {     
  echo 'Yesterday';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号