Search code examples
phplaravelunixphp-carbon

PHP Carbon incorrectly formatting UNIX timestamp


I receive a UNIX timestamp from a URL like so:

/api/v1/order_variations/60?d=1508364000000

When I retrieve and try to convert the timestamp into a readable format, Carbon outputs the incorrect date.

$timestamp = (int)$request->input('d');
$date = Carbon::createFromTimestamp($timestamp)->format('j F, Y');
dd($date);

The value of $timestamp is 1508364000000.

Carbon converts this to "25 February, 49768" but it should be "19 October, 2017"

If I use:

Carbon::createFromTimeStampUTC($timestamp)->toDateTimeString(); 

I get the same result.

Any ideas what I could be doing wrong?


Solution

  • Unix timestamps is the number of seconds since the epoch (1 January 1970), but you're using the number of milliseconds. Just divide the value with 1000 to get the number of seconds.

    $timestamp = (int)$request->input('d');
    $timestamp = intval($timestamp / 1000); // convert milliseconds to seconds
    

    This results in the value "18 October 2017 22:00:00". The only way to get the value "19 October 2017" from this would be to use a timezone with a +02:00 offset (CEST? SAST? Africa/Johannesburg?).