Converts string date and time to unix time - Node.js Date

Node.js examples for Date:Date Format

Description

Converts string date and time to unix time

Demo Code


/**//from  w ww . jav a2 s  .  c  o  m
 * Converts string date and time to unix time
 *
 * @param {string} time - Timecode, format hh:mm:ss.ms
 * @param {string} [date] - Date, format yyyy-mm-dd
 * @returns {number} Unix time
 */
exports.stringToUnix = function(time, date){
    "use strict";

    var unix = 0;

    var timeRegExp = /(\d{1,2}):(\d{2}):(\d{2})\.(\d{2})/;
    var dateRegExp = /(\d{4})\-(\d{2})\-(\d{2})/;

    // Date
    if (typeof date != "undefined") {
        var dateMatches = dateRegExp.exec(date);

        if (dateMatches == null) {
            throw new Error("Date format error: " + date + " (expects 0000-00-00)");
        }

        unix += Date.UTC(
            parseInt(dateMatches[1]),
            parseInt(dateMatches[2]) - 1,
            parseInt(dateMatches[3]),
            0,
            0,
            0,
            0
        );
    }

    // Time
    var timeMatches = timeRegExp.exec(time);

    if (timeMatches == null) {
        throw new Error("Time format error: " + time + " (expects 00:00:00.00)");
    }

    unix += parseInt(timeMatches[1]) * 60 * 60 * 1000
            + parseInt(timeMatches[2]) * 60 * 1000
            + parseInt(timeMatches[3]) * 1000
            + parseInt(timeMatches[4]) * 10;

    return unix;
};

Related Tutorials