Jeff Winkworth
Jeff Winkworth

Reputation: 4996

php: convert milliseconds to date

I Have a string that is equal to a date, represented as the number of milliseconds since the Unix epoch.

I am trying to output it into d-m-Y.

The string I was given was "1227643821310", and I am told that the result should be equal to 2-12-2008, but I keep getting a result of 25-11-2008

My code is as follows:

$mil = 1227643821310;
$seconds = $mil / 1000;
echo date("d-m-Y", $seconds);

Any ideas as to why this might be?

Upvotes: 65

Views: 129908

Answers (6)

Adonias Vasquez
Adonias Vasquez

Reputation: 1024

$mil = 1227643821310;
$seconds = ceil($mil / 1000);
echo date("d-m-Y", $seconds);

Upvotes: 6

incalite
incalite

Reputation: 3207

For the conversion itself, I use this line: $date = date('d-m-Y H:i:s', $millis / 1000);

Although the answer is simple, I like to post an example snippet for usage as well, so there it is.

Extracting day, month and year from it.

// explode values first in spaces and then in dashes
$date = explode('-', explode(' ', $date)[0]); 
$day = $date[0];
$month = $date[1];
$year = $date[2];

Use them as you like: echo $day . '-' . $month . '-' . $year;

Output: dd-mm-yyyy

Upvotes: 0

DanielOpaluwa
DanielOpaluwa

Reputation: 351

I just added H:i:s like in the below example:

$mil = 1227643821310;
$seconds = $mil / 1000;
echo date("d/m/Y H:i:s", $seconds);

Upvotes: 35

Ilya Birman
Ilya Birman

Reputation: 10072

Jeff, the important thing to understand when dealing with timestamps: they represent time which have passed from 0:00:00 01.01.1970 in GMT, not in your timezone (unless you are youself in GMT, of course).

1227643821 indeed represents the GMT time of 20:10:21 25.11.2008.

This is November 25th, 2008 in most of the world, however in timezones to the east of Moscow (and in the Moscow timezone itself in summer because of daylight savings time) it’s already November 26th. Since the most “extreme” east time zone is GMT+14, there’s no place in the world where the timestamp of 1227643821 can represent a date later then the 26th.

Author of the original value may have somehow mistaken when dealing with timezones. Or just plain mistaken. For example, when calculating the value, added seconds instead of milliseconds at some step.

Upvotes: 2

Patrick Glandien
Patrick Glandien

Reputation: 7851

You are already doing it right, 1227643821 is simply not 02-12-2008, it is indeed 25-11-2008.

Upvotes: 61

Scott Vander Molen
Scott Vander Molen

Reputation: 6439

The only thing I can think of is try rounding off the decimal portion before converting it to a date. If that doesn't change the result, then the result is correct.

Upvotes: 1

Related Questions