Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!