Reputation: 2781
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
Upvotes: 21
Views: 37794
Reputation: 272096
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
Upvotes: 3
Reputation: 27364
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");
Upvotes: 4
Reputation: 173552
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);
Upvotes: 25