Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()}`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading