Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly calculate remaining time in JS using getTime() from the two dates?

I'm trying to calculate remaining time (ex: 10 years, 2 months and 10 days from today(2014/03/02) in JS using this function:

var d2 = new Date(2024, 3, 12);
var d1 = new Date();
var d0 = new Date(1970, 0, 1);

var diff = new Date(d2.getTime() - (d1.getTime() + d0.getTime() ) );
var years = diff.getFullYear();
var months = diff.getMonth();
var days = diff.getDay();

alert("remaining time = " + years + " years, " + months + " months, " + days + " days.");

But instead of get the 10 years difference, I got 1980 years difference (though the days difference I understand that are produced buy the variation of days in months and years):

enter image description here

Is it possible to perform this "remaining time" operation using this strategy? If so, how to get the expected result?

Here the function in a JS shell: jsfiddle.net/3ra6c/

like image 769
craftApprentice Avatar asked Mar 02 '14 17:03

craftApprentice


People also ask

How can I calculate the time between 2 dates in TypeScript?

To calculate the time between 2 dates in TypeScript, call the getTime() method on both dates when subtracting, e.g. date2. getTime() - date1. getTime() . The getTime() method returns a number representing the milliseconds between the unix epoch an the given date.


1 Answers

I find here the solution I was looking for:

var date1 = new Date();
var date2 = new Date(2015, 2, 2);
var diff = new Date(date2.getTime() - date1.getTime());

var years = diff.getUTCFullYear() - 1970; // Gives difference as year
var months = diff.getUTCMonth(); // Gives month count of difference
var days = diff.getUTCDate()-1; // Gives day count of difference

alert("remaining time = " + years + " years, " + months + " months, " + days + " days.");

And it seems to work very well!

like image 62
craftApprentice Avatar answered Sep 19 '22 22:09

craftApprentice