问题
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