1

Hi I am delivering a UTC time from the server to the client's browser. The time shows up correctly but the timezone does not. Here is how the time is showing up:

Tue Jul 15 2014 19:35:00 GMT-0500

The date and time are correct but the time zone is not. I just want to change the GMT -0500 to UTC. When I change it to UTC then I can convert it to local time.

Al Lelopath
  • 6,448
  • 13
  • 82
  • 139
Luke101
  • 63,072
  • 85
  • 231
  • 359
  • http://stackoverflow.com/questions/85116/how-do-i-display-a-date-time-in-the-users-locale-format-and-time-offset – AmmarCSE Jul 15 '14 at 21:14
  • If the time shows up correctly in the wrong timezone, then the original datetime is not correct. Parse it correctly as UTC, and use UTC output methods. – Bergi Jul 15 '14 at 21:16

1 Answers1

5

Even though you're receiving a UTC time, the javascript object will always show up as the local time in the console. For example:

var date = new Date(1405458751062);

Outputs this for me:

Tue Jul 15 2014 17:12:31 GMT-0400

You have to take that date object and output the specific properties.

For example in UTC:

date.getUTCFullYear() + "-" + (date.getUTCMonth() + 1) + "-" + date.getUTCDate() + " " + date.getUTCHours() + ":" + date.getUTCMinutes();

Outputs:

2014-7-15 21:12

Or local time:

date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes();

Outputs:

2014-7-15 17:12

To me it seems like you are parsing in your date incorrectly because 19:35 hasn't come around yet. You need to make sure your date is parsed correctly so that when you output the date object to the console (ex. console.log(date)), it will display the date in your browser's local time. From there you must format the date properly in UTC using a method similar to above.


I would suggest using Moment.js though. It makes life easy:

var date = moment(1405458751062); 
date.toString();         // returns Tue Jul 15 2014 17:12:31 GMT-0400
date.utc().toString();   // returns Tue Jul 15 2014 21:12:31 GMT+0000
date.local().toString(); // returns Tue Jul 15 2014 17:12:31 GMT-0400

The library makes it very easy to format dates as well.

David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • Careful. If you go down the path of building the string from individual parts, you'll need to add 1 to the month fields, as the `Date` object uses months 0-11 instead of 1-12. You might also want to zero-pad each field. +1 for the moment.js solution though. – Matt Johnson-Pint Jul 17 '14 at 15:46
  • @MattJohnson Fixed. I forgot about that months were zero-indexed in javascript (probably because I've been formatting dates with moment.js for so long now haha) – David Sherret Jul 17 '14 at 16:02