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

145
Visualizações
Easy way to parse "February 03, 2022 at 04:52PM" into Date in Javascript

Apologies, I'm a noob with Javascript and I couldn't see any easy way to parse February 03, 2022 at 04:52PM into a Date object.

The best I can think of is using Regex to split each part of the string into it's own component and then create a new Date object. But I'll need a switch statement to parse the month also.

I need to do this in plain JS, no libraries.

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

0

I ended up doing this the hard way. I wish Javascript supported the C standard date and time specifiers to parse date strings, but I guess this will have to do:

jsfiddle

function getDateObj(inputStr){

  const monthObj = {
    'Jan':0,
    'Feb':1,
    'Mar':2,
    'Apr':3,
    'May':4,
    'Jun':5,
    'Jul':6,
    'Aug':7,
    'Sep':8,
    'Oct':9,
    'Nov':10,
    'Dec':11,
  };

  const regexMonth = /(...).*/;
  const regexDate = /.*?\ ([0-9]{2}).*/;
  const regexYear = /([0-9]{4})/;
  const regexHour = /([0-9]{2}):[0-9]{2}(AM|PM)/;
  const regexMin = /[0-9]{2}:([0-9]{2})(AM|PM)/;
  const regexAmpm = /[0-9]{2}:[0-9]{2}((AM|PM))/;
  const month = monthObj[inputStr.match(regexMonth)[1]];
  const date = parseInt(inputStr.match(regexDate)[1]);
  const year = parseInt(inputStr.match(regexYear)[1]);
  const hour = parseInt(inputStr.match(regexHour)[1]);
  const min = parseInt(inputStr.match(regexMin)[1]);
  const ampm = inputStr.match(regexAmpm);

  let realHour = 0;
  if (ampm[1] === 'PM') {
    realHour = parseInt(hour) + 12;
  } else {
    realHour = parseInt(hour);
  }

  const dateObj = new Date(year, month, date, hour, min, 0);
  return dateObj;
}

console.log(getDateObj('February 03, 2022 at 04:52PM').toString());
// "Thu Feb 03 2022 04:52:00 GMT+X (XXX Standard Time)"
about 4 years ago · Juan Pablo Isaza Relatório

0

Well with moment.js you can parse your string as it is and define the formatting. Head over to the librarys' page and open the dev console to play with it!

basically you do want to do this:

const date = moment('February 03, 2022 at 04:52PM', 'MMMM DD, YYYY at hh:mm A')
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