cant get the datetime difference in javascript(nodejs)

244 views Asked by At

I am trying to get the day/hr/min difference from two JavaScript datetime stamps, the current time subtract a future event time which will then be displayed on the application front end.

two dates: Future event date - 2017-10-01 18:00:00 Current date - now()

Current code:

var currentTime = new Date();
var eventStarts = results[0][i].eventstarts;
var difference = differenceInMilliseconds(eventStarts, currentTime);
var date = new Date(difference);
var days = date.getDay();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var formattedTime = days + ':' + hours + ':' + minutes.substr(-2);

This isn't correctly working and i cant figure out why, its returning a 2 day difference which obviously isn't correct, it should be returning upwards of 29 days.

I'm currently using the npm package date-fns and i don't mind trying out another package if that will help out

1

There are 1 answers

2
Orelsanpls On BEST ANSWER

When you have a Date, it's based on the 1st january 1970. So when you are setting up new Date(difference). You are setting a date related to 1st january 1970 - so not what you are looking for.

I would recommand you to use the library moment.js, that allow easy date manipulation.


@manzurul example Here

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);

console.log(d.days(), d.hours(), d.minutes(), d.seconds());