日期和時間戳相互轉換

/**
 * @param {string} date //"2020-01-02"
 * @returns {string}    //1577894400
 */
date2timestamp: (date)=>{
    date = new Date(date.replace(/-/g, '/')); //兼容firefox
    return Math.round(date / 1000); //秒級時間戳
},

/**
 * @param {string} timestamp //"1577894400"
 * @returns {string}    //"2020-01-02"
 */
timestamp2date: (timestamp)=>{
    let date = new Date(timestamp * 1000);//時間戳爲10位需*1000,時間戳爲13位的話不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    let D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
    let h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
    let m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
    let s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
    return Y+M+D+h+m+s;
},
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章