Boardy
Boardy

Reputation: 36227

DateTime->format(epoch) returning the wrong date

I am working on a project and I am having an issue formatting an epoch time to a human readable time.

I have the following epoch time 1428512160 and when I put this through epochconverter.com I get the human time of 08/04/2015 17:56:00 GMT+1:00 DST as expected.

I then use the following code in order to perform the conversion from the epoch time to a human date time.

$dt = new DateTime($supportDetails["Reported"]);
$reportedTimeString = $dt->format('d-m-Y H:i:s');

$supportDetails[Reported] is the epoch time (I've printed it so I know it's correct).

The result I get back however is 08-04-2160 14:28:51.

Upvotes: 2

Views: 1128

Answers (4)

Madness
Madness

Reputation: 2726

The problem I see is with your formatting.

If you look at PHP's date function you can see that you just need to write each portion of the desired date & time into a string.

The following formatting gives the same output you were looking for:

$dt = new DateTime($supportDetails["Reported"]); $reportedTimeString = $dt->format('d/m/Y H:i:s \G\M\TP T');

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

You need to add an @ for the timestamp in the DateTime class, like this:

$dt = new DateTime("@" . $supportDetails["Reported"]);
                  //^ See here

You can also see this in the manual. And a quote from there:

Unix Timestamp "@" "-"? [0-9]+ "@1215282385"

Also note that the current timezone is getting ignored, which you can also see in the manual:

Note: The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Upvotes: 8

user3740097
user3740097

Reputation:

Try the following code:

$reportedTimeString = date("d-m-Y H:i:s", $supportDetails["Reported"]);

Or the following:

$date = new DateTime();
$date->setTimestamp($supportDetails["Reported"]);
$reportedTimeString = $date->format("d-m-Y H:i:s");

Upvotes: 0

prashant thakre
prashant thakre

Reputation: 5147

Printing date and time is correct. Its based on what GMT you have set in your PHP. If you printing with GMT you will get required result.

Upvotes: 0

Related Questions