Parsing dates using localtimezone to date object in javascript

断了今生、忘了曾经 提交于 2019-12-11 20:36:32

问题


I want to parse a date into a javascript date object. I am using the following

new Date(Date.parse('2012-08-01'))

The problem is my input date can be in multiple formats and parsing it should always give me the date object with the date as

2012-08-01 00:00:00

in local timezone.

What are possible options in javascript without using any third party libraries ?

I have a possible solution. But my concern is should i be worried that this will not work in certain android/iphone/kindle/surface native browsers?

var timezone = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1];
var dateObject = new Date(Date.parse('2012-08-01 '+timezone));

回答1:


Replace the dashes with forward slashes and it will use the local time. Be sure to use yyyy/mm/dd ordering if you want it to work everywhere.

You also do not need to explicitly call Date.parse. The Date constructor will do that when you pass a string.

new Date('2012/08/01')  // local
new Date('2012-08-01')  // UTC

Yes, JavaScript is weird.



来源:https://stackoverflow.com/questions/24052034/parsing-dates-using-localtimezone-to-date-object-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!