Home > Enterprise >  Format Date FR and Date US to iso date
Format Date FR and Date US to iso date

Time:10-18

I have a function who receive different format date. This function can receive two format:

2022-06-04

or

04/06/2022

I will like to have the same format like:

2022-06-04

For example:

public getMaxduration(data: object[]): number {


 data.forEach((line) => {
  const periodFrom = new Date(line['period_to'];
  const periodTo = new Date(line['period_from'];

  console.log(periodFrom);
  console.log(periodTo);

 })

}

My problem is, if I receive a date with the format dd/mm/yyyy that don't work. So how can I format all date in this function to the format yyyy-mm-dd ?

CodePudding user response:

You could use regular expressions to check what the input format is, then create an array of [year, month, day] values from the input string using String.split(). If the input date is in the form day/month/year, we'll reverse this to get the correct values.

Once we have year, month, day, we'll use map and join to return the correct output format.

function reformatDate(input) {
    let a = [];
    if (/\d{4}-\d{1,2}-\d{1,2}/.test(input)) {
        a = input.split('-'); // yyyy-M-d
    } else if (/\d{1,2}\/\d{1,2}\/\d{4}/.test(input)) {
        a = input.split('/').reverse(); // d/M/yyyy
    } else {
        throw new Error('Unknown date format:', input);
    }
    return a.map(s => s.padStart(2, '0')).join('-');
}

const inputs = ['2022-10-18', '2022-08-23', '18/10/2022', '31/2/2019'];

console.log('Input'.padEnd(12), 'Output')
inputs.forEach(input => { 
    console.log(input.padEnd(12), reformatDate(input))
})

CodePudding user response:

two option

1.use moment

return moment(new Date(dateInput)).format('YYYY-MM-DD');

2.or this

const date = new Date(dateInput);
return date.getFullYear()   "-"   date.getMonth()   "-"   date.getDay();
  • Related