user1701252
user1701252

Reputation: 1571

Convert Epoch Time to Date PHP

I'm using an API right now and it provides an epochTime. I've tried everything to convert this epochtime to date, but it doesn't seem to be working including $epoch_time / 1000 and then using the date() function to convert it.

The epoch time looks something like this 1353430853299. Is there a way to do this? strtotime() did not work either.

It seems that all of the other readings about epoch time are about changing date to epochtime, but I'm looking to go the other way around. Any help is greatly appreciated.

Upvotes: 53

Views: 101772

Answers (7)

Number1 Dad
Number1 Dad

Reputation: 21

This works when you divide by 1000:

echo date("Y-m-d H:i:s", round(1353430853299/1000))

In this example, you will get 1353430853.299, so you must round it to get rid of the fractional part of the number. You could also use floor if you don't want it rounded.

Upvotes: 2

Manjeet Kumar Nai
Manjeet Kumar Nai

Reputation: 1570

You need to select only 10 digits from epoch format

<?php echo date("Y-m-d H:i:s", substr("1621157545307", 0, 10)); ?>

output will be like :

2021-05-16 15:02:25

Upvotes: 2

user1701252
user1701252

Reputation: 1571

Fixed it using substr($epoch, 0, 10) and then used the date function for anyone wondering about the 13 digit epoch times.

Here is a sample code:

echo date("Y-m-d H:i:s", substr("1477020641000", 0, 10));
// Result: 2016-10-20 20:30:41

Upvotes: 77

Rawkode
Rawkode

Reputation: 22592

<?php
$epoch = '1353429562';

date_default_timezone_set('GMT');
echo date('Y-m-d H:i:s', $epoch);

Upvotes: 14

foxontherock
foxontherock

Reputation: 1841

FYI, API that send JSON data use epoch with millisecondes to be compatible with web browsers.

I don't know why PHP needs to remove the millisecondes, as it is the standard for every web browser.

So, you can use the left 10, or / 1000 (it's better to divide by 1000 if you don't want to get troubles on Nov 20, 2286!!!)

Upvotes: 2

Jon
Jon

Reputation: 1085

There are a couple different ways you can do this.

First off, what you've got there is a Unix Epoch time. (1/1/1970), that makes everything MUCH easier.

In PHP, try

$epoch = 1344988800;
$dt = new DateTime("@$epoch");
echo $dt->format('Y-m-d H:i:s');

To display your date

OR

If you want the long RFC232 date:

echo date('r', $epoch);

Upvotes: 39

twodayslate
twodayslate

Reputation: 2833

$epoch = 1344988800;
$dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime
echo $dt->format('Y-m-d H:i:s'); // output = 2012-08-15 00:00:00 

More: http://www.epochconverter.com/programming/functions-php.php

Upvotes: 15

Related Questions