Parsing Dates without Time Zone in JavaScript
Parsing dates without a specified time zone in JavaScript can be challenging. The Date.parse() function assumes a local time zone, which can lead to incorrect results depending on the user's current location.
Issue:
To illustrate the issue, consider the following attempts to parse dates without a time zone:
<code class="javascript">new Date(Date.parse("2005-07-08T00:00:00+0000")); // Fri Jul 08 2005 02:00:00 GMT+0200 new Date(Date.parse("2005-07-08 00:00:00 GMT+0000")); // Fri Jul 08 2005 02:00:00 GMT+0200 new Date(Date.parse("2005-07-08 00:00:00 GMT-0000")); // Fri Jul 08 2005 02:00:00 GMT+0200</code>
Regardless of the specified time zone, all attempts return the same result.
Resolution:
To parse dates without a time zone, you can use the following steps:
<code class="javascript">var date = new Date('2016-08-25T00:00:00') var userTimezoneOffset = date.getTimezoneOffset() * 60000; var parsedDate = new Date(date.getTime() + userTimezoneOffset);</code>
The getTimezoneOffset() function returns a positive or negative value, which needs to be subtracted to ensure the date is adjusted accurately.
The above is the detailed content of How to Parse Dates in JavaScript Without a Time Zone?. For more information, please follow other related articles on the PHP Chinese website!