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

How to Parse and Format ISO 8601 Dates in JavaScript?

DDD
DDDOriginal
2024-10-27 01:38:30665browse

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

You can parse it using the following code:

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

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>

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!

Statement:
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