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

How to Parse Date Strings in \'dd.mm.yyyy\' format in JavaScript?

Linda Hamilton
Release: 2024-10-28 09:56:02
Original
892 people have browsed it

How to Parse Date Strings in 'dd.mm.yyyy' format in JavaScript?

Parsing Date Strings in dd.mm.yyyy Format

Parsing date strings in a specific format can be a frequent task in JavaScript. Specifically, let's focus on handling dates in the 'dd.mm.yyyy' format.

To achieve this, we can use the powerful 'Date' object in combination with the 'String.split' method. Here's how:

var strDate = "03.09.1979"; // Input date string

// Split the string into its individual components: day, month, year
var dateParts = strDate.split(".");

// Create a new Date object using the parsed components
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
Copy after login

In this code:

  1. The 'strDate' variable holds the input date string in the 'dd.mm.yyyy' format.
  2. 'String.split' breaks down the string by the delimiter ('.'), resulting in an array called 'dateParts' containing three elements: day, month, and year.
  3. The 'Date' object constructor accepts three parameters: year, month (0-indexed), and day. Note that the month is adjusted by subtracting 1 to align with the JS convention where months are zero-based.
  4. The resulting 'date' variable now represents the parsed date in JavaScript Date object form.

Refer to the Mozilla Core JavaScript Reference for the 'Date' object and 'String.split' method for further documentation. This technique provides a robust and efficient way to handle date strings in the 'dd.mm.yyyy' format in JavaScript.

The above is the detailed content of How to Parse Date Strings in \'dd.mm.yyyy\' format 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