Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP strtotime and JavaScript Date.parse return different timestamps

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
like image 733
Naresh Avatar asked Feb 14 '13 04:02

Naresh


People also ask

Why is Strtotime return false?

strtotime expects a "English textual datetime" (according to the manual), which Y-D-M is not. Any time strtotime returns false, it simply doesn't understand your string, which in this application is expected.

What does Strtotime return in PHP?

PHP strtotime() function returns a timestamp value for the given date string. Incase of failure, this function returns the boolean value false.

How do I convert Strtotime to date format?

Code for converting a string to dateTime $input = '06/10/2011 19:00:02' ; $date = strtotime ( $input ); echo date ( 'd/M/Y h:i:s' , $date );


2 Answers

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);
like image 160
Ja͢ck Avatar answered Sep 23 '22 20:09

Ja͢ck


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");
like image 28
Dipesh Parmar Avatar answered Sep 25 '22 20:09

Dipesh Parmar