Skip to content Skip to sidebar Skip to footer

How To Extract Only Time From Iso Date Format In Javascript?

let isoDate = '2018-01-01T18:00:00Z'; I need to extract only 18:00 using any method event moment.

Solution 1:

You can use regular expressions to match for that specific area.

let isoDate = '2018-01-01T18:00:00Z';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);

Solution 2:

Vanilla Javascript implementation.

const dateObj = new Date('2018-01-01T18:00:00Z');
let hour = dateObj.getUTCHours();
let minute = dateObj.getUTCMinutes();

console.log(hour, minute);

This make use of Date built-in Javascript Object. If you don't want to add an external library for this sole purpose, you should check it out.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


Solution 3:

You could do it using momentjs.

By default, moment parses and displays in local time. If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment()

var t = moment.utc("2018-01-01T18:00:00Z").format("HH:mm")
console.log(t)
<script src="https://cdn.jsdelivr.net/npm/moment@2.19.3/moment.min.js"></script>

Solution 4:

Here is a quick, one-line solution in plain JavaScript:

console.log("2018-01-01T18:00:00Z".replace(/^[^:]*([0-2]\d:[0-5]\d).*$/, "$1"));

If the date you get is an instance of Date rather than a string, then you can convert it easily using toISOString as shown below:

let date = new Date('2018-01-01T18:00:00Z');
console.log(date.toISOString().replace(/^[^:]*([0-2]\d:[0-5]\d).*$/, "$1"));

Solution 5:

I received the date as follows and to grab the time this worked for me

let isoDate= '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);

The output will be only the time from isoDate which is,

15:27

Post a Comment for "How To Extract Only Time From Iso Date Format In Javascript?"