Helper functions to convert epoch time to and from JavaScript Date objects.


/**
 * Converts a Date object to Epoch.
 *
 * @param {Date} date The Date object to convert to epoch time. If not
 *     specified, a new Date object will be created with current time.
 * @param {Boolean} isGmt If true, will use local time without attempting the
 *     offset.
 *
 * @return {Int} The date as epoch time.
 */
function dateToEpoch(date, isGmt) {
    date = date || new Date();
    if (isGmt) {
        var epochTime = parseInt(
                Date.UTC(
                    date.getUTCFullYear(),
                    date.getUTCMonth(),
                    date.getUTCDate(),
                    date.getUTCHours(),
                    date.getUTCMinutes(),
                    date.getUTCSeconds(),
                    date.getUTCMilliseconds()
                ) / 1000);
        return epochTime;
    } else {
        var epochTime = (date.getTime() - date.getMilliseconds()) / 1000;
        return epochTime;
    }
}

/**
 * Converts an Epoch time value to a Date object.
 *
 * @param {Int} epoch The epoch time.
 *
 * @return {Date} The epoch time value as a JavaScript Date object.
 */
function epochToDate(epoch) {
    var epochTime = parseInt(epoch);
    var date = new Date();

    // Convert to milliseconds
    // Epoch is usually expressed in seconds, but Javascript uses milliseconds.
    if (epochTime < 10000000000) {
        epochTime *= 1000;
    }

    date.setTime(epochTime);

    return date;
}