Node.JS 时间戳与字符串的相互转换

/**
 * 字符时间转时间戳(返回毫秒)
 */
function strTimeToTimeStamps(strtime) {
    //时间转换
    var date = new Date(strtime);
    //获取时间戳
    var timeStamps = Date.parse(date);
    return timeStamps;
}

/**
 * 时间戳转字符时间
 * @param {*} nTimeStamps 
 */
function timeStampsToStrTime(nTimeStamps) {
    //转毫秒
    var date = new Date(nTimeStamps);
    //时间字符串
    var timeString = date.getFullYear() + "-" +
        (date.getMonth() + 1) + "-" +
        date.getDate() + " " +
        date.getHours() + ":" +
        date.getMinutes() + ":" +
        date.getSeconds() + ":" +
        date.getMilliseconds();
    return timeString;
}

//字符串转时间戳
var timeStamps = strTimeToTimeStamps("2020-12-16 14:20:00");
//输出日志
console.log("timeStamps=%d", timeStamps);           //输出:timeStamps=1608099600000
//时间戳转字符串
var timeString = timeStampsToStrTime(timeStamps);
//输出日志
console.log("timeString=%s", timeString);           //输出:timeString=2020-12-16 14:20:0:0

 

你可能感兴趣的:(node,javascript,node.js,时间戳,字符串,转换)