Luke101
Luke101

Reputation: 65298

How to convert a UTC time to local time

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.

Upvotes: 1

Views: 11276

Answers (1)

David Sherret
David Sherret

Reputation: 106830

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.

Upvotes: 6

Related Questions