-3

I am getting date of last n days from today by using a function -

function get_date_of_last_n_days_from_today(n){
  return new Date(Date.now() - (n-1) * 24 * 60 * 60 * 1000);
}

SO if run above code to get the date of previous 3rd day from today (included) then I will use get_date_of_last_n_days_from_today(3)

But the output of above returns -
Sun Oct 31 2021 09:59:58 GMT+0530 (India Standard Time)

I want to convert output in only YYYY-MM-DD How do I do this ?

diana
  • 39
  • 6
  • 3
    Does this answer your question? [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – barzin.A Nov 02 '21 at 04:34
  • Adding or subtracting days as multiples of 24 hours fails in places where some days aren't 24 hours long (e.g. daylight saving changeover days). See [*Add days to JavaScript Date*](https://stackoverflow.com/questions/563406/add-days-to-javascript-date). And why `(n - 1)`? `get_date_of_last_n_days_from_today(1)` will return today, not yesterday. – RobG Nov 02 '21 at 10:44

2 Answers2

1

You could use these methods from the date object and format it yourself

function get_date_of_last_n_days_from_today(n) {
  const date = new Date();
  date.setDate(date.getDate() - n);
  const pad = n => n.toString().padStart(2, '0');

  const yyyy = date.getFullYear(),
    mm = pad(date.getMonth() + 1),
    dd = pad(date.getDate());

  return `${yyyy}-${mm}-${dd}`;
}

console.log(get_date_of_last_n_days_from_today(3));

or use libraries like dayjs or date-fns to simplify

// dayjs
function get_date_of_last_n_days_from_today(n) {
  return dayjs().subtract(n, 'day').format('YYYY-MM-DD');
}

// date-fns
function get_date_of_last_n_days_from_today(n) {
  return format(subDays(new Date(), n), 'yyyy-MM-dd');
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
0

I would do it like so.

const day = 24 * 60 * 60 * 1000;
const padZeros = (num, places) => String(num).padStart(places, '0');

function get_date_of_last_n_days_from_today(n) {
  const date = new Date(Date.now() - (n - 1) * day);
  return `${date.getFullYear()}-${padZeros(date.getMonth() + 1, 2)}-${padZeros(date.getDate(), 2)}`;
}

This date formatting process is however, a lot easier when using libraries such as day.js.

Anga
  • 19
  • 4