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 ?
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');
}
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.