Skip to content

Instantly share code, notes, and snippets.

@ohaal
Last active December 30, 2015 10:29
Show Gist options
  • Save ohaal/7816592 to your computer and use it in GitHub Desktop.
Save ohaal/7816592 to your computer and use it in GitHub Desktop.
Return milliseconds until a specified date string (very specific use case)
function _parseDate(input) {
var re = /^(?:(?:(\d{1,2})[\/.\\-](\d{1,2})(?:[\/.\\-]((?:\d{2}|\d{4})))?(?:\D(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?)?)|(?:(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?))$/;
var time = re.exec(input);
var year, month, day, hour, minute, second;
var future, now;
var curDate = new Date();
var unixCurDayOfMonth = new Date(curDate.getFullYear(), curDate.getMonth(), curDate.getDate()).getTime();
var unixCurTime = curDate.getTime();
if (time) {
var yearIsNotDefined = (typeof time[3] === 'undefined');
var dateIsNotDefined = (typeof time[1] === 'undefined');
year = parseInt(time[3] || curDate.getFullYear(), 10);
if (year < 100) {
year += 2000;
}
month = parseInt(time[2] || curDate.getMonth()+1, 10);
day = parseInt(time[1] || curDate.getDate(), 10);
hour = parseInt(time[4] || time[7] || 0, 10);
minute = parseInt(time[5] || time[8] || 0, 10);
second = parseInt(time[6] || time[9] || 0, 10);
var unixReqTime = new Date(curDate.getFullYear(), curDate.getMonth(), curDate.getDate(), hour, minute, second).getTime();
if ((unixCurTime > unixReqTime) && dateIsNotDefined) {
day += 1;
}
var unixReqDayOfMonth = new Date(year, month-1, day).getTime();
var todayIsAfterRequestedDay = (unixCurDayOfMonth > unixReqDayOfMonth);
var todayIsSameAsRequestedDayButEarlierInTheDay = (unixReqDayOfMonth == unixCurDayOfMonth && unixReqTime < unixCurTime);
if ((todayIsAfterRequestedDay || todayIsSameAsRequestedDayButEarlierInTheDay) && yearIsNotDefined) {
year += 1;
}
future = new Date(year, month-1, day, hour, minute, second).getTime();
}
else {
future = 0;
}
now = Date.now();
if (future - now < 0) {
return 0;
}
else {
return future - now; // milli
}
}
var testcases = [
"18/10/2014 18:00:11", //0
"18/10/2014 18:00", //1
"18/10/2014@18:00", //2
"18/10@18:00:11", //3
"18/10T18:00", //4
"18/10/2015", //5
"18/10/04/18:00", //6 (should be 0)
"00:12", //7
"18/10", //8
"05/12 22:20", //9
"18/07T18:00" //10 (test summer time)
];
for (i in testcases) {
console.log(i + ": " + _parseDate(testcases[i]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment