tjcinnamon
tjcinnamon

Reputation: 375

Convert ISO Date to UTC Time using JavaScript

I have an ISO Date string and using Javascript, I'd like to extract the time from it.

How can I turn 2016-07-02T19:27:28.000+0000 into 7:27 pm? I have tried Date.Parse with little success

Upvotes: 1

Views: 31162

Answers (5)

Vedran Mandić
Vedran Mandić

Reputation: 1356

Just don't use moment.js or any dependency what so ever, why use a dependency?

Simple:

new Date(new Date().toUTCString()).toISOString().split("T")[1].split(".")[0];

Upvotes: 4

anonymous
anonymous

Reputation: 1701

Here is how you can do it with moment js

moment('2016-07-02T19:27:28.000+0000').format('MMMM Do YYYY, h:mm:ss a');

Upvotes: 0

Pulkit Aggarwal
Pulkit Aggarwal

Reputation: 2672

You can first get the date in UTC format

var utcDate = new Date("2016-07-02T19:27:28.000+0000").toUTCString();

Get the time from utcDate.

var time = utcDate.split(' ')[4];

Conver the 24 hr time format to 12 hr format using getDesireTime function.

function getDesireTime(time) {
     hr = parseInt(time.split(':')[0]);
     amOrpm = hr < 12 ? 'AM' : 'PM'; // Set AM/PM
     hr = hr % 12 || '00'; // Adjust hours
     return`${hr}:${time.split(':')[1]} ${amOrpm}`
 }
console.log(getDesireTime(time));

Upvotes: 2

Hector Barbossa
Hector Barbossa

Reputation: 5528

Please take a look at toTimeString and toLocaleTimeString. You can use them like below.

var d = new Date("2016-07-02T19:27:28.000+0000");
console.log(d.toLocaleTimeString());
console.log(d.toTimeString());

Upvotes: 3

estefano valdez
estefano valdez

Reputation: 34

You can use moment.js, it´s the best date library I have worked with.

Upvotes: 1

Related Questions