Home > Software engineering >  Detect format of date in Javascript
Detect format of date in Javascript

Time:09-12

Currently we have multiple date formats in our database:

DD/MM/YYYY
DD-MM-YYYY
YYYY/MM/DD
YYYY-MM-DD

We all want to format these to one format YYYY-MM-DD. When using dayjs to do this I'm getting NaN-NaN-NaN back when running dayjs('14/05/1993').format('YYYY-MM-DD')

We can add a format to dayjs by adding the customParseFormat plugin

dayjs.extend(customParseFormat)
dayjs('14/05/1993', 'DD/MM/YYYY').format('YYYY-MM-DD')

But how can we detect the format for all four formats we have?

(Solution may be without dayjs)

CodePudding user response:

String Format

If you know the format of an input string, you can use that to parse a date.

This dependent on CustomParseFormat plugin to work

dayjs.extend(customParseFormat) dayjs("12-25-1995", "MM-DD-YYYY")

Pass the locale key as the third parameter to parse locale-aware date time string.

require('dayjs/locale/es') dayjs('2018 Enero 15', 'YYYY MMMM DD', 'es')

You may specify a boolean for the last argument to use strict parsing. Strict parsing requires that the format and input match exactly, including delimiters.

dayjs('1970-00-00', 'YYYY-MM-DD').isValid() // true
dayjs('1970-00-00', 'YYYY-MM-DD', true).isValid() // false
dayjs('1970-00-00', 'YYYY-MM-DD', 'es', true).isValid() // false

If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.

dayjs("12-25-2001", ["YYYY", "YYYY-MM-DD"], 'es', true);

Source: https://day.js.org/docs/en/parse/string-format

With that...

const possibleDateFormats = ["DD/MM/YYYY", "DD-MM-YYYY", "YYYY/MM/DD", "YYYY-MM-DD"];

dayjs('14/05/1993', possibleDateFormats).format('YYYY-MM-DD');

CodePudding user response:

This should solve your problem as long as your date format is consistent

function dateFormatter(dateString) {
      
      if (dateString.includes('-')) {
            const splittedDate = dateString.split('-');
            if (splittedDate[2].length === 4) {
                 return splittedDate.reverse().join('-')
            }
            else {
                  return splittedDate.join('-')
            }


      } else {
            const splittedDate = dateString.split('/');
            if (splittedDate[2].length === 4) {
                 return splittedDate.reverse().join('-')
            }
            else {
                  return splittedDate.join('-')
            }
      }

}


console.log(dateFormatter('2020/15/5'))

  • Related