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

How to Parse and Format ISO 8601 Dates in JavaScript?

DDD
Release: 2024-10-27 01:38:30
Original
771 people have browsed it

How to Parse and Format ISO 8601 Dates in JavaScript?

Parsing ISO 8601 Dates in JavaScript: A Comprehensive Guide

When working with dates, it's crucial to understand how to parse them from various formats. One common format encountered across the web is ISO 8601, which follows a standard structure for representing dates and times.

Parsing ISO 8601 Dates

To parse an ISO 8601 date in JavaScript, you can leverage the Date object, which can handle ISO 8601 strings as its first parameter. For instance, given the following ISO 8601 date:

2014-04-07T13:58:10.104Z
Copy after login

You can parse it using the following code:

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

Customizing Date Format

After parsing the date, you may want to format it in a specific way. The toString() method of the Date object provides a default representation of the date. However, to customize the format, you can use a third-party library or create your own formatting function.

For example, to format the parsed date as "January 28, 2011 - 7:30PM EST," you could use the following custom format:

January <DD>, <YYYY> - <HH>:<\MM><AM>\<\PM> <TZ>
Copy after login

Where:

  • represents the day of the month (e.g., 28)
  • represents the year (e.g., 2011)
  • represents the hour (e.g., 19 for 7:30PM)
  • represents the minute (e.g., 30)
  • represents the meridian (e.g., PM)
  • represents the timezone (e.g., EST)

Conclusion

Parsing ISO 8601 dates in JavaScript is straightforward using the Date object. By utilizing custom formatting techniques, you can tailor the output to your specific requirements. Remember to test your parsing and formatting logic thoroughly to ensure accurate and consistent results.

The above is the detailed content of How to Parse and Format ISO 8601 Dates 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