PHP strtotime and JavaScript Date.parse return different timestamps

35,862

Solution 1

You need to use the same time-zone for a sane comparison:

echo strtotime("2011-01-26 13:51:50 GMT");
// 1296049910

var d = Date.parse("2011-01-26 13:51:50 GMT") / 1000;
console.log(d);
// 1296049910

Update

According to the standard, only RFC 2822 formatted dates are well supported:

Date.parse("Wed, 26 Jan 2011 13:51:50 +0000") / 1000

To generate such a date, you can use gmdate('r') in PHP:

echo gmdate('r', 1296049910);

Solution 2

JavaScript uses milliseconds as a timestamp, whereas PHP uses seconds. As a result, you get very different dates, as it is off by a factor 1000.

sample

echo date('Y-m-d', TIMESTAMP / 1000);

Comment Response

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

    function toTimestamp(year,month,day,hour,minute,second)
    {
        var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
        return datum.getTime()/1000;
    }

    $(function()
    {
        console.log(toTimestamp(2011,01,26,13,51,50));

    });

</script>

<?php

echo $the_date = strtotime("2011-01-26 13:51:50");

Solution 3

strtotime() and Date.parse() yield UNIX timestamps with a resolution of seconds and milliseconds respectively. However, if timezone information is missing from the input string, local time is assumed. So the input string 2011-01-26T13:51:50 may produce different output on different machines even if PHP (or JavaScript) is used to generate the timestamps on both machines.

The solution is to explicitly specify the timezone in the strings. This should produce the same result on any machine:

Date.parse("Jan 26, 2011 13:51:50 GMT+0500") / 1000; // 1296031910
strtotime("Jan 26, 2011 13:51:50 GMT+0500");         // 1296031910
Share:
35,862

Related videos on Youtube

Naresh
Author by

Naresh

profile for Puzzled Boy on Stack Exchange, a network of free, community-driven Q&amp;A sites http://stackexchange.com/users/flair/2100519.png

Updated on February 15, 2020

Comments

  • Naresh
    Naresh about 4 years

    I am getting same date time seconds value in JavaScript which is given by strtotime() in PHP. But i need same value in JavaScript.

    PHP Code

    echo strtotime("2011-01-26 13:51:50");
    // 1296046310
    

    JavaScript Code

    var d = Date.parse("2011-01-26 13:51:50");
    console.log(d);
    // 1296030110000
    
  • Ja͢ck
    Ja͢ck about 11 years
    That's not the only difference :)
  • Dipesh Parmar
    Dipesh Parmar about 11 years
    @jack i know TIMEZONE also does matter but i just give second difference because first was already given by you
  • Chinmay235
    Chinmay235 over 8 years
    Coming NaN in Mozilla browser.