0

I am getting a date formatted this way:

18th February

And after adding weeks, should come back in the same format example:

input => 18th February + 7 weeks:

output => 31st March

I am able to get the date and add weeks but I am finding very complicate to format the date back.

This is what I have right now:

let date = new Date(("18th February").replace(/st|rd|nd|th/g, ""))

let weeks = 7 * 7

let newDate = date.setDate(date.getDate() + weeks)

console.log(new Date(newDate))

//Output

2001-03-31T23:00:00.000Z

//Desire Output

//31st March

Thank you for you help.

Mario Garcia
  • 113
  • 1
  • 1
  • 6
  • Probably you are searching this- https://stackoverflow.com/questions/11591854/format-date-to-mm-dd-yyyy-in-javascript – Raju Ahmed Mar 08 '21 at 14:40

1 Answers1

-1

I think date formatting in the Front-End isn't really good so libraries always help (like momentjs, datefnz, etc..)

But you could add this to your code to make it work:

let date = new Date(("18th February").replace(/st|rd|nd|th/g, ""))

let weeks = 7 * 7

let newDate = new Date(date.setDate(date.getDate() + weeks))

let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
let month = months[newDate.getMonth()]
let day = newDate.getDate()

function dayWithNth (d) {
  if (d > 3 && d < 21) return `${d}th`;
  switch (d % 10) {
    case 1:  return `${d}st`;
    case 2:  return `${d}nd`;
    case 3:  return `${d}rd`;
    default: return `${d}th`;
  }
}

console.log(`${dayWithNth(day)} ${month}`)
  • `new Date(("18th February")` should be strongly discouraged, it produces an invalid Date in at least one current browser. – RobG Mar 08 '21 at 20:43
  • That's true, thanks for pointing that out. I actually just used his code and added 1 way to get the format Mario wanted. Cheers. – Jose Pernia Mar 08 '21 at 21:27