Last active
April 7, 2016 10:07
-
-
Save marcelkornblum/103c57c191eadb1dbeb205bee4fb4135 to your computer and use it in GitHub Desktop.
Fairly naive JS function for guessing a date from a variety of natural language strings. Includes regexes!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getDateFromString( input ) { | |
var d = new Date(); | |
var this_year = d.getUTCFullYear(); | |
var date_obj = new Date(input); // try just the default | |
if ( _.isDate(date_obj) && _.isFinite(date_obj.getTime()) && date_obj.getUTCFullYear() >= this_year ) { // well that was easy | |
return date_obj; | |
} | |
input_int = _.parseInt(input); | |
if ( input_int > this_year && input_int < this_year + 3 ) { // guess we've just got a year numeral | |
var date_obj = new Date(input_int, 0, 1); | |
if ( _.isDate(date_obj) && _.isFinite(date_obj.getTime()) ) { // whatever we've got is a real date | |
return date_obj; | |
} | |
} | |
// we're going to have to get funky to find a date here... | |
var months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']; | |
input = _.trim( input ); | |
input = _.lowerCase( input ); | |
// is there a month in the string? | |
var match = _.find(months, function (month) { | |
return input.match(new RegExp(month.substr(0, 3), 'i')); | |
}); | |
if ( match !== undefined) { | |
var month_index = _.indexOf(months, match); | |
// get a number we can assume is a day - this will be the first numebr found | |
var day_date = input.match(/\d{1,2}/i); | |
if ( day_date === null ) { | |
// no specific day | |
if ( input.match(/begin/i) === null && input.match(/start/i) === null ) { | |
//let's assume the end of the month | |
day_date = 0; | |
month_index += 1; | |
} | |
else { | |
//let's assume the start of the month | |
day_date = 1; | |
} | |
} | |
else { | |
if ( input.match(/w c/i) !== null ) { | |
// end of the specified week | |
d = new Date(this_year, month_index, day_date); | |
day_date = d.getDate() - d.getDay() + 5; | |
} | |
} | |
return new Date(this_year, month_index, day_date); | |
} | |
var q_match = input.match(/q (\d{1})/i); | |
if ( q_match !== null) { | |
month_index = _.parseInt(q_match[1]) * 3; | |
return new Date(this_year, month_index, 0); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment