DateUtility.js

/**
 * Get date only with time part set to zero
 * @param  {Date} date Date object/Timestamp
 * @return {Date}      Date object
 */
function getDateOnly(date) {
    date = new Date(date);
    return new Date(date.setHours(0,0,0,0));
}

/**
 * Get date only with time part set to zero
 * @param  {Date} date Date object/Timestamp
 * @return {Date}      Date object
 */
function getDateEnd(date) {
    date = new Date(date);
    return new Date(date.setHours(23,59,59,999));
}

/**
 * Convert timestamp from local timezone to GMT
 * @param  {Date} date Date/Timestamp
 * @return {Number}      Timestamp in GMT
 */
function getGmtTimestamp(timestamp, offset) {
    // Convert local time to GMT
    timestamp = timestamp + (offset * 60 * 1000);
    return timestamp;
}

/**
 * Compare dates without comparing time
 * @param  {Date} date1 Date object/Timestamp
 * @param  {Date} date2 Date object/Timestamp
 * @return {Number}     Difference in dates after setting time to zero
 */
function compareDateOnly(date1, date2) {
    date1 = getDateOnly(date1);
    date2 = getDateOnly(date2);

    var oneday = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var diff   = (date1.getTime() - date1.getTime())/ oneday;

    return diff;
}

/**
 * Check if the given date falls between from and to date
 * @param  {Date}  date            Date to be compared
 * @param  {Date}  fromDate        From Date
 * @param  {Date}  toDate          To Date
 * @param  {Boolean} isFromInclusive Is from date inclusive
 * @param  {Boolean} isToInclusive   Is to date inclusive
 * @return {Boolean}                 [description]
 */
function isBetweenDates(date, fromDate, toDate, isFromInclusive, isToInclusive) {
    var isWithinRange = false;

    date        = new Date(date);
    fromDate    = getDateOnly(fromDate);
    toDate      = getDateEnd(toDate);

    if(isFromInclusive) {
        isWithinRange = date >= fromDate && date < toDate;
    }
    else if(isToInclusive) {
        isWithinRange = date > fromDate && date <= toDate;
    }
    else if(isFromInclusive && isToInclusive) {
        isWithinRange = date >= fromDate && date <= toDate;
    }
    else {
        isWithinRange = date > fromDate && date < toDate;
    }

    return isWithinRange;
}

module.exports = {
    getDateOnly: getDateOnly,
    getDateEnd: getDateEnd,
    getGmtTimestamp: getGmtTimestamp,
    compareDateOnly: compareDateOnly,
    isBetweenDates: isBetweenDates
};