Home > Web Front-end > JS Tutorial > body text

How to Parse a Date Without a Timezone in JavaScript?

Susan Sarandon
Release: 2024-10-25 16:03:02
Original
776 people have browsed it

How to Parse a Date Without a Timezone in JavaScript?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template