We would like to create a function getDateAgo(date,days)
to return the day of month days ago from the date.
For instance, if today is 20th, then *getDateAgo(new Date()
,1)* should be 19th.
*getDateAgo(new Date()
,2)* should be 18th.
The function cannot modify the given date.
let date = new Date(2020, 0, 2); console.log( getDateAgo(date, 1) ); // 1, (1 Jan 2020) console.log( getDateAgo(date, 2) ); // 31, (31 Dec 2019) console.log( getDateAgo(date, 365) ); // 2, (2 Jan 2019)
Code: function getDateAgo(date, days) { let dateCopy = new Date(date); dateCopy.setDate(date.getDate() - days); return dateCopy.getDate(); } let date = new Date(2020, 0, 2); console.log( getDateAgo(date, 1) ); // 1, (1 Jan 2020) console.log( getDateAgo(date, 2) ); // 31, (31 Dec 2019) console.log( getDateAgo(date, 365) ); // 2, (2 Jan 2019)