Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda