27

Javascript:

I have object cell with something date

params.date = cell.getDate();
params.timestamp = cell.getDate().getTime() / 1000;
console.log(params);

Object {date: Thu May 09 2013 00:00:00 GMT+0800 (China Standard Time), timestamp: 1368028800}

Then I try to check timestamp in PHP

$date = '1368028800';
echo date('Y-m-d', $date);

2013-05-08

Difference in one day. Why?

3 Answers 3

29

When you get timestamp from Javacript date object :

it output will be interms of milli-seconds

 <script>
        var d = new Date();
        alert(d.getTime());

     </script>

output : 1386746353000

Where as php date object timestamp interms of seconds

<?php 
        $date = new DateTime();
        echo $current_timestamp = $date->getTimestamp();
     ?>

output : 1386746353

So when you are going to use javascript date object timestamp with php date object you should divide timestamp of javascript by 1000 and use it in php

Sign up to request clarification or add additional context in comments.

3 Comments

Note: dividing a timestamp by 1000 in javascript will yield a float. To get an integer ~~(Date.now()/1000)
You can , probably, use parseInt(Date.now() / 1000)
It's been recommended in another answers to use Math.floor(datevar.getTime()/1000)
11
params.date = cell.getDate();

Returns the DATE not the TIME.

params.timestamp = cell.getDate().getTime() / 1000;

is converting the date into a date+time - not reading the current time.

But even if you get the timestamp in javascript, the output of PHP's date function will depend on what timezone it is in.

2 Comments

Thanks. I have UTC timezone in PHP and Chinese timezone on client. How I should modify javascript?
@indapublic you should convert your client time to UTC, possibly you could also ask the server what time it thinks it is and use that to determine how off your client is
3

The UNIX Timestamp 1368028800 corresponds to the date Wed, 08 May 2013 16:00:00 GMT. In your example, you are on the China Standard Time (GMT+8), so Javascript display the datetime for this timezone (8 hours later -> 09 May)

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.