How to Parse Date Without Timezone in JavaScript
Parsing dates without timezones can be challenging in JavaScript. Attempts such as:
<code class="javascript">new Date(Date.parse("2005-07-08T00:00:00+0000")); new Date(Date.parse("2005-07-08 00:00:00 GMT+0000")); new Date(Date.parse("2005-07-08 00:00:00 GMT-0000"));</code>
all return a date with the Central European Daylight Time (GMT 0200) offset. This is because JavaScript interprets dates without timezones as being in the local timezone.
To parse a date without a timezone and without using a constructor, you can use the following technique:
<code class="javascript">var date = new Date('2016-08-25T00:00:00'); var userTimezoneOffset = date.getTimezoneOffset() * 60000; var utcDate = new Date(date.getTime() + userTimezoneOffset);</code>
The getTimezoneOffset() method returns the user's timezone offset in minutes. Multiplying this value by 60000 converts it to milliseconds, which can be added to the date's getTime() value to create a UTC Date object.
This technique will work for all timezones and can be used to parse dates without constructors or prototype approaches.
The above is the detailed content of How to Parse a Date Without a Timezone in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!