Unable to convert data '19-10-2002' into date

Viewed 360

I need to pass a date parameter in format (dd-MM-yyyy) and convert in this format (yyyy-MM-dd) to send API.

So I do this:

convert(date:string){
date //is in the format(dd-MM-yyyy)

date =formatDate(date , "yyyy-MM-dd", 'en_US');

and I obtain this error:

 Unable to convert "19-10-2002" into a date

Anyone can help me?

3 Answers

You could just do

console.log(
"19-10-2002".split('-').reverse().join('-')
)

If you want to pass a string to "formatDate" it has to be in "ISO date-time" format (the complete format is "YYYY-MM-DDThh:mm:ss.sTZD", but you can drop any part from the end and use like "YYYY" or "YYYY-MM-DD"). so the string you are passing to it is not recognized as a valid input date. so you can use Dave's code

Here is the custom date formatter function which accepts date, format and separator/delimiter to convert the passed date with passed format.

function dateFormatter(date, format, delimiter) {
  const dateItems = date.split(delimiter)
  const formatItems = format.toLowerCase().split(delimiter);
  const day = formatItems.indexOf('dd');
  const month = formatItems.indexOf('mm');
  const year = formatItems.indexOf('yyyy');
 
  const formattedDate = ([dateItems[day], dateItems[month], dateItems[year]]).join(delimiter)
  console.log(formattedDate)
  return formattedDate
}

// run example
dateFormatter('02-03-2020', 'YYYY-MM-DD', '-');
dateFormatter('02/03/2020', 'MM/DD/YYYY', '/');

Related