Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
convert date in YYYY-MM-DD in javascript

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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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');
}
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!