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?
You are already doing it right, 1227643821 is simply not 02-12-2008, it is indeed 25-11-2008.
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);
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.
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.
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)); $day = $date; $month = $date; $year = $date;
Use them as you like:
echo $day . '-' . $month . '-' . $year;