Home > database >  convert date in YYYY-MM-DD in javascript
convert date in YYYY-MM-DD in javascript

Time:11-02

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 ?

CodePudding user response:

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(), 2)}-${padZeros(date.getDay(), 2)}`;
}

CodePudding user response:

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 yyyy = date.getFullYear(),
    mm = date.getMonth()   1,
    dd = date.getDate()

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

console.log(get_date_of_last_n_days_from_today(3));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

var d = new Date()
d.setMonth(d.getMonth() - 2);
var dateString = new Date(d);
console.log('Before Format', dateString, 'After format',dateString.toISOString().slice(0,10))
  • Related