Raghu
Raghu

Reputation: 5

Difference in UTC date between PHP and Javascript

I have a date string in PHP, say, $min_date = "2012-03-30"

If I run this date through the javascript Date.UTC function, I get 1333065600000. This is the value I want.

var split_date = min_date.split('-');
Date.UTC(split_date[0],(parseInt(split_date[1])-1),split_date[2]); //gives 1333065600000

I am unable to get this value in PHP.

strtotime($min_date); //gives 1333045800

mktime(23,60,60,intval($split_date[1]),intval($split_date[2]),intval($split_date[0])); //gives 1333132260

How do I get the value from PHP that I get in javascript? I'd rather do this conversion on server side and send it to the client as these dates come in a large array that will be painful to convert on client side.

PS: My server time is set correctly.

Upvotes: 0

Views: 1370

Answers (4)

Glavić
Glavić

Reputation: 43552

You don't get correct timestamp in PHP because of the timezone difference. Set timezone to UTC and you will have the same output as javascript :

# globally
date_default_timezone_set('UTC');
echo strtotime('2012-03-30') . "\n";

# or like @Jim said, only for single operation :
echo strtotime('2012-03-30 UTC') . "\n";

Even better solution is to use DateTime class :

$dt = new DateTime($date, new DateTimeZone('UTC'));
echo $dt->getTimestamp() . "\n";

Upvotes: 3

Amal Murali
Amal Murali

Reputation: 76646

It's because your timezone is set incorrectly. You need to set your timezone to UTC. And then, you can use DateTime class and get the required timestamp as follows:

$date = new DateTime('30-03-2012', new DateTimeZone('UTC'));
$ts = $date->getTimestamp()*1000;
echo $ts;

Output:

1333065600000

Demo!

Upvotes: 0

Jim
Jim

Reputation: 22656

As Glavic mentioned this is due to your timezone not being UTC.

An alternative to changing the timezone setting globally is to simply pass UTC into strtotime:

strtotime($min_date. " UTC"); 

Upvotes: 0

Olegacy
Olegacy

Reputation: 61

<script>
  var serverTime = new Date("<?php echo date('M d, Y H:i:s') ?>");
</script>

Upvotes: 0

Related Questions