Thank you in advance
I would like your help with getting 'days ago' from a particular date
. I don't want to use any library.
Although I have tried moment JS
.
Thank you in advance
I would like your help with getting 'days ago' from a particular date
. I don't want to use any library.
Although I have tried moment JS
.
Use getDate()
and subtract the number of days from it
var d = new Date();
d.setDate(d.getDate() - 6);
console.log(d);
First, make a new Date with your date:
const date = new Date('December 17, 1995 03:24:00');
Second, subtract 6 days like so:
date.setDate(date.getDate() - 6);
Third, use date.toString()
:
console.log(date.toString());
You question title and description contradict with each other. The following function that return number of days ago can help if this is what you need:
function getDaysAgo(date, now = new Date()) {
//first calculating start of the day
const start = now.setHours(0, 0, 0, 0);
//then calculating difference in miliseconds
const diff = start - date.getTime();
//finally rounding to a bigger whole days
const result = Math.ceil(diff/(1000*60*60*24));
//as a bonus returning today/yesterday/future when necessary
if (result < 0) {
return 'in future';
}
if (result === 0) {
return 'today';
}
return result === 1 ? 'yesterday' : result + ' days ago';
}
For example getDaysAgo(new Date(Date.parse('2019-9-28 23:59')), new Date(Date.parse('2019-9-30 10:59'))) returns 2 days ago.
It is a simple function that returns a new desire past date.
function getNthDate(nthDate){
let date = new Date();
return new Date(date.setDate(date.getDate() - nthDate))
}
Live example