js时间戳与时间的相互转化

来源:互联网 发布:pyqt4安装 linux 编辑:程序博客网 时间:2024/06/05 04:35

    //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);        }    };