"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 to Parse and Format ISO 8601 Date Strings in JavaScript?

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

Published on 2024-11-19
Browse:676

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:

var d = new Date("2014-04-07T13:58:10.104Z");

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:

console.log(d.toLocaleString("en-US", {
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  timeZoneName: "short",
}));

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.

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