Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime/DateInterval adding 25 hours each refresh gives a completely different result

Here is my code:

$timezone = new \DateTimeZone('America/New_York');
    $date1 = new \DateTime (date("Y:m:d H:i:s", time()), $timezone);
    $date1->add(new \DateInterval ("PT24H"));
    echo $date1->format('Y-m-d h:s:m');

This should add 24 hours to the current time. Problem is, each time I refresh the page, I get a different result. And I don't mean by just a couple seconds like one would expect, I mean lots of minutes. Some above the actual time some below it.

Three refreshes right now at 9:51pm give the following results: 2013-03-26 09:09:03, 2013-03-26 09:17:03, 2013-03-26 09:30:03

Why can't I get the real time? What is going on?

Thanks for the help!

like image 904
user1513171 Avatar asked Mar 26 '13 01:03

user1513171


1 Answers

The error is in your last echo statement

echo $date1->format('Y-m-d h:s:m');

change this to:

echo $date1->format('Y-m-d h:i:s');

Every refresh is refreshing the middle value which you had set to seconds rather than minutes therefore every 3 second update for example was showing to you as a 3 minute update. In addition you had your minute showing as m which is the date format for month number so it was showing as 3 for the numerical representation of March. I have changed this to i to represent minutes.

I got your code above working here in London with the following code:

$date1 = new DateTime('America/New_York');
$date1->add(new DateInterval("PT24H"));
echo $date1->format('Y-m-d h:i:s');

This now shows 10:07 PM March 26th which is 24 hours after the current time in New York

like image 58
Peter Featherstone Avatar answered Nov 15 '22 08:11

Peter Featherstone