Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Unix timestamp TO date with offset

11:36 am on Apr 13, 2012 (gmt 0)

10+ Year Member

Hello All -

Brain-wracking issue here.

I've got a PHP-generated UNIX timestamp that I feed to a javascript function. This function then formats and displays the date to the user.

For example, the timestamp 1335024000 equals April 22, 2012 - 12:00:00 am - 00:00 and the javascript function I wrote spits out "22 Apr". Perfect.

That is, it's perfect for users in my timezone (Manila, Philippines).

If the user is in New York City, (I've tested this by re-setting the timezone on my computer to (UTC-05:00) Eastern Time) the php time stamp stays the same, but Javascript spits out "21 Apr". Arg!

Here's my javascript code:

var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var stamp = 1335024000;
var a = new Date(stamp*1000);
var date = a.getDate();
var month = months[a.getMonth()];

I've investigated getTimezoneOffset() and, it does give a -5 hour offset from UTC, but I don't understand how to alter my code to accommodate this offset.

Will getTimezoneOffset() correct this issue? If not, how does one deal with this issue?

All guidance greatly appreciated.

alert(date + ' ' + month);

Okay, so javascript is doing something based upon the users timezone settings.

I've studied
1:56 pm on Apr 13, 2012 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

The JavaScript Date constructor that you're using is passing in the the number of milliseconds since 1 January 1970 00:00:00 UTC.

Lets calculate the difference.

var jan_1_1970 = new Date(1970, // year
0, // month
1, // day
0, // hour
0, // minute
0, // second
0); // millisecond
var apr_22_2012 = new Date(2012,
var difference = apr_22_2012.getTime() - jan_1_1970.getTime();
// difference = 1335049200000 != 1335024000000

In other words, your stamp value is incorrect. It is off by 7 hours.
1335049200000 - 1335024000000 = 25200000 ms
25200000ms / 1000 = 25200 seconds
25200 s / 60 = 420 minutes
420 m / 60 = 7 hours
1:54 am on Apr 16, 2012 (gmt 0)

10+ Year Member

Fotiman -

Thanks very much for your reply.

That's very unusual as the time stamp I'm using always keeps coming up with the same result as I had posted initially UNLESS I change the php timezone ini setting. This is something I'm going to have to investigate further on the php forum.

At any rate, I have found a work-around which yields the correct date display no matter what timezone the users system clock is set to.

Thanks again for your guidance.