0

I have a date in following format:

13 Dec,2021 12:59:58

and I want to change it into:

13-12-2021

pls suggest some fix

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • 2
    Hi, please read [how to ask](https://stackoverflow.com/help/how-to-ask). – Brendan Bond Dec 06 '21 at 05:13
  • 1
    There are a huge number of questions about [parsing a string to a Date](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+parse+a+date+string), and probably just as many on [how to format a date](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date). Try something, and if you have trouble, post what you've tried, what you're trying to achieve and what you actually get. – RobG Dec 06 '21 at 08:43

3 Answers3

0

Convert it do a Date, get the make a string out of the components.

The month needs to add 1 since for some reason, months are zero-indexed (January == 0, February == 1, ..., December == 11)

const dateString = "13 Dec,2021 12:59:58";

const getNewString = (dateString) => {
  const date = new Date(dateString);
  return `${date.getDate()}-${date.getMonth()+1}-${date.getFullYear()}`;
}

console.log(getNewString(dateString));
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
0

You can do something like this

const oldDate = "13 Dec,2021 12:59:58";

const newDate = new Date(oldDate);

console.log(newDate.getDate() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getFullYear());
Neel Dsouza
  • 1,342
  • 4
  • 15
  • 33
0

You can use moment.js to do this.

console.log(moment('13 Dec,2021 12:59:58').format('DD-MM-YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>