How can I get time from ISO 8601 time format in JavaScript?

Viewed 9702

This is my ISO formatted date. In here I want to get time like "11:00" by JavaScript. I used this method:

new Date(Mydate).toLocaleString();

But it gave time as "16:30". Is there any format or method to do that in JavaScript? How can I get only time of that time zone.

var Mydate = "2012-10-16T11:00:28.556094Z";

Output will be the "11:00"

6 Answers

Try this to grab the time from ISO date.

let Mydate = '2012-10-16T11:00:28.556094Z';
let result = Mydate .match(/\d\d:\d\d/);
console.log(result[0]);

The output will be,

11:00

be aware that older implementation of the toLocaleTimeString can behave differently depending on the browser's implementation.

Date: 2021-September-09

The locales and options arguments customize the behavior of the function and let applications specify which language formatting conventions should be used. In older implementations that ignore the locales and options arguments, the locales and the form of the string returned will be entirely implementation-dependent.

The implementation I recently used:

function getTimeFromISODateString(isoDateString) {
  const date = new Date(isoDateString);
  const hours = `0${date.getUTCHours()}`.slice(-2);
  const minutes = `0${date.getUTCMinutes()}`.slice(-2);
  const seconds = `0${date.getUTCSeconds()}`.slice(-2);
  return `${hours}:${minutes}:${seconds}`;
}
Related