Skip to content

Instantly share code, notes, and snippets.

@ninapavlich
Created March 25, 2020 22:37
Show Gist options
  • Save ninapavlich/ae15555acbc342168910875382cf4337 to your computer and use it in GitHub Desktop.
Save ninapavlich/ae15555acbc342168910875382cf4337 to your computer and use it in GitHub Desktop.
Multiple date format parser regex
var possibleDateFormats = [
'Updated on 3/25, 9:35PM',
'Updated on 03/25, 9:35PM',
'Updated 3/25/2020, 9:35PM',
'Updated 3/25/2020 at 9:35PM',
'Updated 3/25/2020 at 9:35 p.m.',
'Updated 3/25 21:35',
'updated on 03/25/20 21:35 PM'
]
const dateRegex = /update(.+)? (\d{1,2})[\/.-](\d{1,2})[\/.-]?(\d{2,4})?(,?|\sat?)\s(\d{1,2}):(\d{1,2})\s?((a|p)\.?m\.?)?/i
const dm = dateText.match(dateRegex);
const year = dm[4]? dm[4].length ==4? parseInt(dm[4]) : parseInt('20'+dm[4]) : 2020;
const rawHour = parseInt(dm[6])
const hour = rawHour > 12? rawHour-12 : rawHour;
const ampm = dm[9]?( dm[9].toLowerCase().includes('a')? 'AM' : 'PM'): rawHour<12? 'AM' : 'PM';
//Now in standard format MM/DD/YYYY HH:MM AM
const standardizedFormat = `${('0'+dm[2]).slice(-2)}/${('0'+dm[3]).slice(-2)}/${year} ${('0'+hour).slice(-2)}:${('0'+dm[7]).slice(-2)} ${ampm}`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment