Skip to content

Instantly share code, notes, and snippets.

@rococodogs
Created August 7, 2014 23:40
Show Gist options
  • Save rococodogs/6d0cee7e66f6fc3a2a69 to your computer and use it in GitHub Desktop.
Save rococodogs/6d0cee7e66f6fc3a2a69 to your computer and use it in GitHub Desktop.
put a lot of effort into this and ended up not using it. can't get myself to just delete it, even though I can't remember if it even works.
function parseDateString(str, options) {
var options = options || {}
, american = options.american_format
, local = options.local_time
, reg = {}
, sampleDate = new Date()
, y = 0, mo = 0, d = 0, h = 0, mi = 0, s = 0
, days = [
'mon',
'tues?',
'weds?(?:nes)?',
'thurs?',
'fri',
'sat(?:ur)',
'sun'
]
, months = ['jan(?:uary)',
'feb(?:ruary)',
'mar(?:ch)',
'apr(?:il)',
'may',
'june?',
'july?',
'aug(?:ust)',
'sept?(?:e)',
'oct(?:ober)',
'nov(?:ember)',
'dec(?:ember)'
]
;
if ( typeof american === 'undefined' ) {
american = true;
}
if ( typeof local === 'undefined' ) {
local = true;
}
reg['english'] = new RegExp('^((?:'
+ days.join('|')
+ ')(?:day)?)?[\\\s\\\,]{0,2}('
+ months.join('|')
+ '?)[\\\s\\\,]{0,2}(\\\d?\\\d(?:nd|st|th)?)[\\\s\\\,]{0,2}((\\\d{0,4})?)$'
, 'i');
reg['yyyymmdd'] = /^(\d{4})[\-\.](\d{2})[\-\.](\d{2})$/i;
reg['timestamp'] = /^(\d{4})\-(\d{2})\-(\d{2})[T\s]?(\d{2})\:(\d{2})\:(\d{2})\-?(\d{2}\:00)?$/i;
reg[(american ? 'mmddyyyy' : 'ddmmyyyy')] = /^(\d?\d)[\/\-\.](\d?\d)[\/\-\.]?(\d{4})?/i;
for ( r in reg ) {
var m = str.match(reg[r]);
if ( m ) {
if ( reg[r] === reg['english'] ) {
d = parseInt(m[3]);
y = parseInt(m[4]) || sampleDate.getFullYear();
months.forEach(function(r, idx) {
if ( m[2].match(new RegExp(r, 'i')) ) {
mo = idx;
}
});
} else if ( reg[r] === reg[(american ? 'mmddyyyy' : 'ddmmyyyy')] ) {
mo = (american === true ? m[1] : m[2]) - 1;
d = (american === true ? m[2] : m[1]);
y = m[3] || sampleDate.getFullYear();
} else {
y = parseInt(m[1]);
mo = parseInt(m[2]) - 1;
d = parseInt(m[3]);
h = m[4] ? parseInt(m[4]) : 0;
mi = m[5] ? parseInt(m[5]) : 0;
s = m[6] ? parseInt(m[6]) : 0;
}
return Date.UTC(y, mo, d, h, mi, s) + (local ? (sampleDate.getTimezoneOffset() * 60000) : 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment