Search code examples
phpdateformatutcstrtotime

UTC date not changing in IST date format in PHP


As based on REST API page documentation the date is in UTC format as yyyy-MM-dd’T’HH:mm:ss (Eg: 2017-01-02T08:12:53) When I hit the API, I am getting the date as 1619693307000. Converted this date using strtotime() in PHP. What is the correct way to convert this date in d-m-Y h:i:s IST in PHP.

I used this code to do the same.

<?php echo date("Y-m-d h:i:s", '1619693307000') ?> //OUTPUT: 53296-01-14 01:00:00 

The above output is absolutely wrong. Confusion is to correctly convert UTC to IST zone and what should i do to see the correct output as the date in PHP. I read all threads on this StackOverflow and Google. but all not helpfull.

Please help...


Solution

  • Your timestamp has too many digits, so it's likely in milliseconds. This seems to be a common javascript thing. So divide by 1000, and I highly recommend using the DateTime objects/interfaces rather than the old-style strtotime()/date()/etc functions.

    $millis = 1619693307000;
    $seconds = $millis / 1000;
    
    $t = new DateTime('', new DateTimezone('Asia/Kolkata'));
    $t->setTimestamp($seconds);
    
    var_dump(
        $t->format("Y-m-d h:i:s T")
    );
    

    Output:

    string(23) "2021-04-29 04:18:27 IST"
    

    Also "UTC" is not a format, it's a timezone. 2017-01-02T08:12:53 is an ISO8601-format. It also has a handy format shortcut:

    var_dump(
        $t->format("c")
    );
    

    Output:

    string(25) "2021-04-29T16:18:27+05:30"
    

    Edit: Different timezone and format:

    $t = new DateTime('', new DateTimezone('UTC'));
    $t->setTimestamp($seconds);
    
    var_dump(
        $t->format("Y-m-d\Th:i:s")
    );
    

    Output:

    string(19) "2021-04-29T10:48:27"