how to get date of yesterday using php?

2020-05-11 16:17发布

I want to get the yesterday date using specific date format in php this is the format:

$today = date("d.m.Y"); //15.04.2013

Is it possible?

Take consideration of month and years if they should be changed in respective.

标签: php date
8条回答
贼婆χ
2楼-- · 2020-05-11 17:04

Step 1

We need set format data in function date(): Function date() returns a string formatted according to the givenformat string using the given integer timestamp or the current time ifno timestamp is given. In other words, timestampis optional anddefaults to the value of time().

<?php
echo date("F j, Y");
?>

result: March 30, 2010

Step 2

For "yesterday" date use php function mktime(): Function mktime() returns the Unix timestamp corresponding to thearguments given. This timestamp is a long integer containing the numberof seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and thetime specified. Arguments may be left out in order from right to left; any argumentsthus omitted will be set to the current value according to the localdate and time.

<?php
echo mktime(0, 0, 0, date("m"), date("d")-1, date("Y"));
?>

result: 1269820800

Step 3

Now merge all and look at this:

<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>

result: March 29, 2010

Operating similarly, it is possible to receive time hour back.

<?php
$yesterday = date("H:i:s",mktime(date("H"), 0, 0, date("m"),date("d"), date("Y")));
echo $yesterday;
?>

result: 20:00:00

or 7 days ago:

<?php
$week = date("Y-m-d",mktime(0, 0, 0, date("m"), date("d")-7,date("Y")));
echo $week;
?>

result: 2010-03-23

查看更多
SAY GOODBYE
3楼-- · 2020-05-11 17:04

you can do this by

date("F j, Y", time() - 60 * 60 * 24);

or by

date("F j, Y", strtotime("yesterday"));
查看更多
登录 后发表回答