Zero
Zero

Reputation: 405

Get yesterday date in php using existing date variable

I have a date code below:

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

My question is how will I get the yesterday time of 2011-01-01 15:00:00. I am currently use this date('Ymd',strtotime("-1 days")) but I think it's not right. What is the best way to get the yesterday date using my first code?

Upvotes: 1

Views: 4432

Answers (4)

anju
anju

Reputation: 609

use this:

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');
echo "\n";
$interval = new DateInterval('P1D');
$date->sub($interval); 
echo $date->format('Y-m-d H:i:s');

Upvotes: 3

vascowhite
vascowhite

Reputation: 18430

You can use the \DateTime::modify() function:-

$date->modify('-1 day');

Or you could subtract a DateInterval:-

$date->sub(new \DateInterval('P1D');

See the DateTime manual for more information.

If you don't want the original $date variable to be modified then you could use DateTimeImmutable instead:-

$date = new \DateTimeImmutable();
$yesterday = $date->sub(new \DateInterval('P1D');

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34924

Use modify function

<?php
$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');
$date->modify('-1 day');
echo "\n";
echo $date->format('Y-m-d H:i:s');
?>

check here : https://eval.in/586553

For more info check this : http://php.net/manual/en/datetime.modify.php

Upvotes: 2

lllypa
lllypa

Reputation: 233

There are tons of answers to this question in the internet and on stackoverflow as well. So, once again:

Use ::modify() method on DateTime: http://php.net/manual/en/datetime.modify.php

$date->modify('-24 hours')
$date->modify('-1 day')

Upvotes: 4

Related Questions