Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate number of days between today and given date and code for getTime()?

I want to calculate number of days between today and a given date and check whether how many days remaining until today or how many days past from today.

var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = today.getTime() - date_to_reply.getTime();
console.log( Math.floor(timeinmilisec / (1000 * 60 * 60 * 24)) );

this gives me 5 as answer but how should i get (-5) since the date_to_reply is 5days past from today?

is this the correct way to calculate any given date?

Regards

like image 457
Gihan Lasita Avatar asked Jan 15 '23 06:01

Gihan Lasita


1 Answers

What you are doing is correct: You want to calculate the difference (as number of days) between two dates. A difference can't be smaller than zero.

Although your date_to_reply is already in the past, theres still a 5 day difference.

So, everythings fine - it's the correct way.

EDIT: If you want a negative value as result, try this:

var today = new Date();
var date_to_reply = new Date('2012-10-15');
var timeinmilisec = date_to_reply.getTime() - today.getTime();
console.log( Math.ceil(timeinmilisec / (1000 * 60 * 60 * 24)) );

Remember you need to Math.ceil the final result instead of rounding it down with Math.floor().

like image 142
Fabian Lauer Avatar answered Feb 06 '23 19:02

Fabian Lauer