Converting an ISO 8601 string to Current TimeZone DateTime Object in Javascript

101 Views Asked by At

I am writing a NodeJS app that sends notification based on recently uploaded youtube videos.

I get this ISO 8601 format string from 2015-06-10T20:18:45.000Z from youtube. That string is the time of a video upload.

How can I take that string, convert it to a Date object of my local time zone, get it's time. Then see how long ago from right now was the video exactly uploaded?

I basically need to know exactly how long ago from right now was the video uploaded. If there is a different way than the once I described above that's fine as well.

I tried this but it doesn't work - because of the Time Zone difference I believe

var temp_one = new Date('2015-06-10T20:18:45.000Z');
var temp_two = new Date();
var difference = temp_two - temp_one
1

There are 1 best solutions below

2
On

What you described will indeed work - as long as the browser supports parsing the ISO8601 formatted string that you are providing. Older browsers (such as IE8) don't support this directly.

The difference variable will return the number of milliseconds elapsed since the date you provided. If you want it in some other units, you can divide the number accordingly:

var seconds = difference / 1000;
var minutes = difference / 60000;
var hours = difference / 3600000;

If you want something more elaborate, you can use moment.js.

For example:

moment("2015-06-10T20:18:45.000Z").fromNow()  // "7 hours ago"