Javascript + 7 days ( Only want yyyy-mm-dd)

I want to change this date to be formatted to DD-MM-YY

new Date(new Date().setDate(new Date().getDate() + 7)))

Current result: Thu Sep 15 2022 02:16:38 GMT+0200 (Central European Summer Time)

Wanted result: 15-09-22

>Solution :

I suggest solving the problem step by step.

  1. Check the Date object documentation. There are methods that return the day, month, and year.

  2. Add leading "0" when you need it. For instance, like this: ${value < 10 ? '0' : ''}${value}.

  3. Concatenate the strings:

`${dayString}-${monthString}-${date.getFullYear()}`
let date = new Date()
date.setDate(date.getDate() + 7);

const day = date.getDate();
const month = date.getMonth();
const dayString = `${day < 10 ? '0' : ''}${day}`;
const monthString = `${month < 10 ? '0' : ''}${month}`;
const formatted = `${dayString}-${monthString}-${date.getFullYear()}`;

Leave a Reply