Home > OS >  Javascript 7 days ( Only want dd-mm-yy)
Javascript 7 days ( Only want dd-mm-yy)

Time:09-08

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

CodePudding user response:

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

CodePudding user response:

const event = new Date(new Date().setDate(new Date().getDate()   7));

var day = event.getDate();
var month = event.getMonth();
var year = event.getFullYear();

var date = day   '-'   month   '-'   year;

date.toString();

I did find a fix for my issues no more comments are necessary

  • Related