-3

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.

Node Shack
  • 59
  • 6
  • The logic here would help https://stackoverflow.com/questions/3818193/how-to-add-number-of-days-to-todays-date – codebarz Sep 30 '19 at 07:21
  • have you even tried looking for the solution? `new Date(new Date().getDate()-days*24*60*60*1000)` – AZ_ Sep 30 '19 at 07:24
  • @AZ_—you might want to try running that to see what happens… – RobG Sep 30 '19 at 12:58
  • how about you tell me what happens? – AZ_ Sep 30 '19 at 13:02
  • If you insist… `new Date().getDate()` will return a number from 1 to 31. Assuming *days* is 6 then `days*24*60*60*1000` is equivalent to 6*8.64e7. So the result is a date for sometime around 26 December, 1969, depending on the date it's run. – RobG Sep 30 '19 at 13:08
  • @RobG typo needed to use `getTime()`, thanks. – AZ_ Oct 01 '19 at 08:37

4 Answers4

2

Use getDate() and subtract the number of days from it

var d = new Date();
d.setDate(d.getDate() - 6);
console.log(d);
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

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());
0

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.

yrazub
  • 1
  • 2
  • Date.parse is redundant in `new Date(Date.parse('2019-9-28 23:59'))` and some browsers treat '2019-9-28 23:59' as an invalid date. – RobG Sep 30 '19 at 13:01
0

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

ptheodosiou
  • 390
  • 3
  • 17