Home > Web Front-end > JS Tutorial > How to Parse and Format ISO 8601 Date Strings in JavaScript?

How to Parse and Format ISO 8601 Date Strings in JavaScript?

DDD
Release: 2024-10-26 02:39:02
Original
429 people have browsed it

How to Parse and Format ISO 8601 Date Strings in JavaScript?

Parsing ISO 8601 Date String in JavaScript

When dealing with dates in JavaScript, you may encounter ISO 8601 date strings, which follow a specific format: CCYY-MM-DDThh:mm:ssTZD. To access and manipulate these dates, let's explore a simple and efficient solution.

Thankfully, the Date object in JavaScript has built-in support for parsing ISO 8601 strings. You can create a new Date object by passing the ISO 8601 string as its first parameter:

<code class="js">var d = new Date("2014-04-07T13:58:10.104Z");</code>
Copy after login

This line of code parses the given ISO 8601 string and creates a Date object representing the specified date and time. You can then access the individual components of the date using the built-in getters:

  • d.getFullYear() for year
  • d.getMonth() for month (0-based)
  • d.getDate() for day of the month
  • d.getHours() for hour (0-23)
  • d.getMinutes() for minutes (0-59)
  • d.getSeconds() for seconds (0-59)
  • d.getMilliseconds() for milliseconds (0-999)
  • d.getTimezoneOffset() for timezone offset in minutes

To format the date in the desired format, you can use the toLocaleString() method:

<code class="js">console.log(d.toLocaleString("en-US", {
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  timeZoneName: "short",
}));</code>
Copy after login

This line of code formats the date as "January 28, 2011 - 7:30PM EST", as per your requirements.

In summary, using the Date object and toLocaleString(), you can easily parse ISO 8601 dates and format them according to your needs. The provided solution keeps it clean and minimal, helping you handle dates efficiently in JavaScript.

The above is the detailed content of How to Parse and Format ISO 8601 Date Strings 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template