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.
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:
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)"