Home > Web Front-end > JS Tutorial > How to Parse Non-Standard DateTime Strings in JavaScript?

How to Parse Non-Standard DateTime Strings in JavaScript?

Linda Hamilton
Release: 2024-11-02 09:45:30
Original
502 people have browsed it

How to Parse Non-Standard DateTime Strings in JavaScript?

Parsing DateTime Strings in JavaScript

In JavaScript, parsing a date string into a DateTime object can be a challenge, especially when the format doesn't match the standard dd-MM-yyyy or MM-dd-yyyy patterns. For instance, consider a date string such as "03.09.1979", where the day and month are separated by a period.

To handle such situations, we need to split the string into its individual components: day, month, and year. The String.Split method can be used for this purpose.

Next, we create a Date object using the extracted components. Note that the month argument in the Date constructor expects the month index (starting from 0), which is why we subtract 1 from the month value obtained from the splitting process.

<code class="javascript">var strDate = "03.09.1979";
var dateParts = strDate.split(".");

var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);</code>
Copy after login

This code snippet effectively parses the "03.09.1979" string into a Date object, allowing subsequent manipulation and formatting of the date as required.

The above is the detailed content of How to Parse Non-Standard DateTime Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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