0

So, I have this 10 Dec, 2019T14:07:21 format of date coming from backend , what I need is to find how many days ago.

like today is 20 , so for todays date it will give 0 days ago.

  • Check this out - https://www.geeksforgeeks.org/how-to-calculate-the-number-of-days-between-two-dates-in-javascript/ – freesoul Dec 20 '19 at 07:17

4 Answers4

1

What you try to do is called "date diff" meaning you want to find the difference in days between 2 dates. First of all you need to create a new Date object from the string you want. You can do that using Moment.js library that will parse your date string and return a Date object.

var date1 = moment("10 Dec, 2019T14:07:21", "DD MMM, YYYY");
var date2 = new Date() //today date

A simple js function accomplishing that is the one below

function dateDiff(date1, date2) {
    var datediff = date1.getTime() - date2.getTime(); 
    return (datediff / (24*60*60*1000));       
}

dateDiff function will return the difference between dates, so if date1 is a previous day, it will return a negative number of days. In order to convert it to the "x days ago" format you need, you need to simply multiply the result by -1.

Petros
  • 342
  • 3
  • 15
  • new Date("10 Dec, 2019T14:07:21") returns "Invalid Date" – user54987 Dec 20 '19 at 07:22
  • Apologies. Date() constructor excepts ans ISO Date formatted string.So you have to convert "10 Dec, 2019T14:07:21" to ISO Date using a library like moment.js – Petros Dec 20 '19 at 08:00
  • I updated the answer explaining how you will convert your string date to Date object using the Moment.js library. – Petros Dec 20 '19 at 08:11
  • @Petros `new Date("10 Dec, 2019T14:07:21".split('T')[0])` works. You cut away the T and anything that follows. Date accepts the string "10 Dec, 2019". (If your date doesn't contain any T that operation won't do anything.) Since you are only interested in days cutting out the time won't do any harm. – MDickten Aug 11 '23 at 08:31
1

You can compare two dates. Substracting them will give you the miliseconds difference. THose miliseconds can be converted into days.

const now = new Date();
// Mimick a backend date
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - 10);
// Compare both, outputs in miliseconds
const diffMs = now - daysAgo;
// Get the number of days by dividing by the miliseconds in a single day
const daysDiff = Math.round(diffMs/(1000*60*60*24));
console.log(daysDiff)
Jeffrey Devloo
  • 1,406
  • 1
  • 11
  • 20
1
(new Date()-new Date("10 Dec, 2019T14:07:21".replace("T"," ")))/1000/60/60/24
user54987
  • 112
  • 8
1

You can try this code.

var date1 = new Date("12/13/2010");
var date2 = new Date("12/20/2010");
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 
console.log(diffDays )
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43