1

In database i have a row with date & time, say 2014-04-16 00:00:00 then I convert that datetime to unix timestamp using

strtotime('2014-04-16 00:00:00') * 1000; // result 1397577600000

In javascript i am trying to get the hour using the following code

var d = new Date(1397577600000); // 1397577600000 from php unix timestamp in previous code
d.getHours(); // return 23
d.getMinutes(); // return 0

why getHours() return 23 instead of 0? is there any difference between js timestamp and php timestamp?

Dariel Pratama
  • 1,607
  • 3
  • 18
  • 49

3 Answers3

2

Date objects in javascript will always return values based on the browser's current timezone. So if d.getHours() is returning 23 for you, that would suggest your local browser timezone is one hour earlier than UTC (-01:00).

It you want the hours for a Date object based on UTC timezone, you can use:

d.getUTCHours()

Follow Up:

Just to throw out some free advice, you could use the following code to deal with your date values from one context to another:

PHP:
// Fetched from the db somehow
$datetime_db = '2014-04-16 00:00:00';

// Convert to PHP DateTime object:
$datetime_obj = new DateTime($datetime_db, new DateTimeZone('UTC'));

// Format DateTime object to javascript-friendly ISO-8601 format:
$datetime_iso = $datetime_obj->format(DateTime::W3C);
Javascript:
var d = new Date('2014-04-16T00:00:00+00:00'); // 2014-04-16T00:00:00+00:00 from PHP in previous code
d.getUTCHours(); // returns 0

This keeps the datetime variables in a language-specific object format when being handled in that language, and serializes the value into a string format that all current browsers/languages accept (the international standard ISO-8601).

Anthony
  • 36,459
  • 25
  • 97
  • 163
0

I am getting 21 here because in Javascript local timezone of the user will be considered to fetch time and date.

void
  • 36,090
  • 8
  • 62
  • 107
0

Ok, based on what Arun P Johnny said.

I change the strtotime parameter to match my timezone, in this case i changed it to

strtotime('2014-04-16 00:00:00 GMT+7') * 1000;

hope this help anybody that have the same problem as I.

Dariel Pratama
  • 1,607
  • 3
  • 18
  • 49