Quick actions

cmd+k|ctrl+k

Navigation

Languages

find milli until some date in the future

Snippet info

Language

JavaScript

Visibility

public

Author

ohaal

Created

2015-07-03T12:52:14Z

Updated

2015-07-03T14:24:14Z

// Return milliseconds until a specified date string
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 (var i in testcases) {
    console.log(i + ": " + _parseDate(testcases[i]));
}
INFO