0

I am trying to format a date in JavaScript to fit a specific format.

My desired format is 29-Jan-2021

With the below code I have managed to generate "29 Jan 2021":

var newDate = new Date('2021-01-29T12:18:48.6588096Z')

const options = {
  year: 'numeric',
  month: 'short',
  day: 'numeric',
};

console.log(newDate.toLocaleString('en-UK', options))

Can someone please show me how I can add - between the day, month, & year in the date above?

user9847788
  • 2,135
  • 5
  • 31
  • 79
  • 1
    Simply take your date string and do `.replaceAll(" ", "-")`. – code Oct 12 '22 at 16:58
  • When I run the code, I don't get any quotation marks. – Heretic Monkey Oct 12 '22 at 17:00
  • Hi @HereticMonkey, I was running it here https://www.w3docs.com/snippets/javascript/how-to-convert-a-string-into-a-date-in-javascript.html, & the quotation marks were appearing. I've upated my question to remove that aspect. Thanks! – user9847788 Oct 12 '22 at 17:00
  • Does this answer your question? [How do I format a date in JavaScript?](https://stackoverflow.com/questions/3552461/how-do-i-format-a-date-in-javascript); specifically, [this answer](https://stackoverflow.com/a/3552493/215552), or [this one](https://stackoverflow.com/a/30272803/215552) – Heretic Monkey Oct 12 '22 at 17:01
  • You could simply use the date as it is and split it on spaces to reformat it as you want in. date = Date().split(" ") console.log(date[2] + "-" + date[1] + "-" + date[3]) – Michael Tétreault Oct 12 '22 at 17:08

1 Answers1

1

Well you if you have already able to find the string close to your answer you can achieve your solution with either of the two methods.

Either you can use replaceAll() or replace(). Both will be able to solve the issue.

let dateFormat = "29 Jan 2021"
console.log(dateFormat.replaceAll(" ","-")) // 29-Jan-2021
console.log(dateFormat.replace(/ /g,"-")) // 29-Jan-2021

Well I would suggest you to use replace() over replaceAll as some browsers do not support replaceAll(). Do check replaceAll support.