"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Convert Strings to Date Objects in JavaScript Reliably?

How Can I Convert Strings to Date Objects in JavaScript Reliably?

Published on 2024-12-22
Browse:691

How Can I Convert Strings to Date Objects in JavaScript Reliably?

Converting Strings to Date Objects in JavaScript

Many scenarios in software development involve working with dates and times. In JavaScript, while creating dates, it's often necessary to convert a string representing a date into a Date object. Below is how to achieve this conversion:

The recommended approach for string parsing is utilizing the ISO format along with the Date object constructor. For example:

var st = "2023-05-09";
var dt = new Date();
var dt_st = new Date(st); // dt_st is a Date object in the same format as dt.

However, merely using the ISO format is insufficient for reliable parsing. Strings may be interpreted as UTC or local time (depending on browser variations). To ensure consistency, it's advisable to store dates in UTC and perform calculations in that format as well.

For parsing dates as UTC, append a "Z" to the string. For instance: new Date('2021-04-11T10:20:30Z')

To display the date in local time, use .toUTCString(), while .toString() can be used for displaying the date in UTC.

For compatibility with older Internet Explorer versions (less than 9), consider splitting the datetime string into components and initializing the Date object with those parts. For instance:

new Date('2011', '04' - 1, '11', '11', '51', '00') 
// Note: the month value must be 1 less than the actual month index (0-based).

Another option is to use libraries like Moment.js, which offer features like date parsing with time zone specification.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3