Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

117
Visualizações
Date parsing from different formats?

I have a string, which can come in different formats:

01.01.2020
01/01/2020
01-01-2020

or
2020-01-01
2020.01.01
2020/01/01


Now if I try doing

const date = new Date(myDateString); 

I will in some cases get an error "Invalid Date". How can I cover all scenarios and transform any scenario into a valid date?

It seems like the new Date(), only takes the format Y-m-y?, even though the other cases are also "valid" dates?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can split the string on the known delimiters and then see whether the first part has four digits. If so, you know it's year-month-day. If not, you know it's month-day-year. You can then construct the date accordingly:

const dateStrings = [
  "10.31.2020",
  "10/31/2020",
  "10-31-2020",
  "2020-10-31",
  "2020.10.31",
  "2020/10/31",
]

function parseDateStr(str) {
  // split on dots, dashes, and slashes
  const parts = str.split(/[./-]/);

  // mm-dd-yyyy
  const [year, month, day] = parts[0].length > 2 ? parts : [parts[2], parts[0], parts[1]];

  // alternate for dd-mm-yyyy
  // const [year, month, day] = parts[0].length > 2 ? parts : parts.reverse();
  
  // construct and return the date. (month is 0 based)
  return new Date(year, month - 1, day);
}

const results = dateStrings.map(parseDateStr);

console.log(results);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can moment to do that. But you need to know which format is used.

https://stackoverflow.com/a/44134515/3573340

about 4 years ago · Juan Pablo Isaza Relatório

0

Date() constructor is accurate if it's parameters are YYYY, MM, DD. The dates of Jan 1, 2020 should go like this:

new Date(2020, 0, 1) // Month is 0 index, so MM -1
  • Given an array of strings .map() and split() each by .-/ delimitters, resulting in sub-arrays of 3 strings from each string:

    strArr.map(str => str.split(/[-./]/))
    
  • then .flatMap() to catch any array that starts with 2 digits and .reverse() it:

    .flatMap(sub => sub[0].length === 2 ? [sub.reverse()] : [sub])
    
  • Finally, .flatMap() each sub-array into the Date() constructor:

    .flatMap(sub => [new Date(+sub[0], +sub[1] - 1, +sub[2])])
    

const jan1_2020 = [
  `01.01.2020`,
  `01/01/2020`,
  `01-01-2020`,
  `2020-01-01`,
  `2020.01.01`,
  `2020/01/01`
];

const formatDate = strArr => strArr.map(str => str.split(/[-./]/)).flatMap(sub => sub[0].length === 2 ? [sub.reverse()] : [sub]).flatMap(sub => [new Date(+sub[0], +sub[1] - 1, +sub[2])]);


let x = formatDate(jan1_2020);
console.log(x);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda