1. 程式人生 > >js時間戳與時間的相互轉化

js時間戳與時間的相互轉化

    //yyyy-mm-dd H:i轉化為時間戳
    var datetime_to_unix = function(date){
        var tmp_datetime = date.replace(/:/g,'-');
        tmp_datetime = tmp_datetime.replace(/ /g,'-');
        var arr = tmp_datetime.split("-");
        var now = new Date(Date.UTC(arr[0],arr[1]-1,arr[2],arr[3]-8,arr[4]));
        return parseInt(now.getTime()/1000);
    }
    //時間戳轉化為當前時間
    var unix_to_datetime = function(x,unix) {
        var date = null;
        if(unix){
            date = new Date(unix);
        }else {
            date = new Date;
        }
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1);
        D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
        h = date.getHours() < 10 ? '0' + date.getHours()  + ':' : date.getHours() + ':';
        m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
        s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
        if(x === 1){return (Y+M+'-'+D+h+m);}//2017-09-29 21:30
        if(x === 4){return (Y+M+'-'+D+h+"00");}//2017-09-29 21:00
        if(x === 2){return (Y+M+'-'+D+"00"+":"+"00");}//2019-09-29 00:00
        if(x === 3){return (Y+M+'-'+D);}//2019-09-29
        if(x === 5){return (Y+M+'-'+"01");}//2019-09-01
        if(x === 6){return (Y+M);}//2019-09
        if(x === 7){return (Y+M+'-'+D+h+m+':'+s);}//精確到秒
        if(x === 0){//取上一個月
            var Y2 = date.getFullYear(); //獲取當前日期的年份
            var M2 = parseInt(date.getMonth());
            if (M2 === 1) {//如果是1月份,則取上一年的12月份
                Y2 = parseInt(Y2) - 1;
                month2 = 12;
            }
            return (Y2+'-'+M2);
        }
    };