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.
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.
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.
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)
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 )