admin管理员组文章数量:1356275
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.
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.
Share Improve this question edited Jul 15, 2014 at 21:09 Al Lelopath 6,78814 gold badges91 silver badges151 bronze badges asked Jul 15, 2014 at 21:06 Luke101Luke101 65.4k88 gold badges242 silver badges374 bronze badges 2- stackoverflow./questions/85116/… – AmmarCSE Commented Jul 15, 2014 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 Commented Jul 15, 2014 at 21:16
1 Answer
Reset to default 6Even 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 e 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.
本文标签: javascriptHow to convert a UTC time to local timeStack Overflow
版权声明:本文标题:javascript - How to convert a UTC time to local time - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744028820a2578533.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论