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