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