21

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

3 Answers 3

25

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Coming NaN in Mozilla browser.
4

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");

2 Comments

That's not the only difference :)
@jack i know TIMEZONE also does matter but i just give second difference because first was already given by you
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.