Search code examples
javascriptecmascript-6date-fns

proper way to format the date depending on scenario


I have a scenario where I can have a date coming as a string. It can be formatted as either:

2021-05-29

29-05-2021

Im using dateFns to parse the strings, but when the string is in the format 2021-05-29, it cant parse the string, which is why, when it has the format of 2021-05-29, it needs to be converted into 29-05-2021...

The parse() function from dateFns what actually what I needed to parse it to the correct format, but it doenst seem to work when passing 2021-05-29

return parse(date, 'mm-dd-yyyy', new Date());

Any ideas what how to handle this?


Solution

  • You could try reversing the date,

    date = date.split(“-“).reverse().join(“-“)