-1

I have a date in the database (firebase realtime database) that I'm fetching and I want to calculate the number of days between the database date and today's date.

I've seen the following answers on stackoverflow.

How do I get the number of days between two dates in JavaScript?

How to calculate the number of days between two dates? [duplicate]

How to get the number of days between two dates?

However, not a single answer helps me because I have different date formats. For instance this is the date format I'm storing in the database:

var date = (new Date()).toDateString().split(' ').slice(1).join(' ');
console.log(date);

and for today's date, it doesn't matter because I only want to get the number of days between these two dates.

I tried multiple ways to convert the date format of that in the database and then using the approach in the mentioned stackoverflow's answer to calculate the number of days but that didn't work.

phuzi
  • 12,078
  • 3
  • 26
  • 50
user1234654
  • 98
  • 11

3 Answers3

2

This should work:

let date = (new Date("Jul 05 2021")).getTime();
let today = (new Date()).getTime();
let msDay = 24 * 60 * 60 * 1000; // milliseconds per day

let days = Math.floor((today - date) / msDay);

Note: "Jul 05 2021" gets constructed in local time zone.

Amith
  • 730
  • 6
  • 22
0

Try the below:

function datediff (date_one, date_two) {
   let day_secs = 24 * 60 * 60 * 1000;
   return Math.ceil((date_two - date_one) / day_secs);
}

Or

const dateDiff= (date, cDate) => Math.ceil(Math.abs(date - cDate) / (1000 * 60 * 60 * 24));
dateDiff(new Date('2021-07-05'), new Date('2020-07-05')); 
  • 2
    The questions linked to in the OP already have many answers showing how to get the difference between two date objects. If you have alternatives to those answers, please add your answer(s) to the those questions, not this one. – Heretic Monkey Jul 05 '21 at 13:47
0

You can use momentjs for this:

const a = moment(date_one);
const b = moment();
const no_of_days = a.diff(b, 'days')