JS---unix时间戳和格式化日期互转

 1.unix时间戳转日期

方法一:
var formatTime=function(timestamp){ //传入时间戳,不传默认为今日
                if(timestamp){
                    var date = new Date(timestamp);
                }else{
                    var date = new Date();
                }
                    Y = date.getFullYear(),
                    m = date.getMonth()+1,
                    d = date.getDate(),
                    H = date.getHours(),
                    i = date.getMinutes(),
                    s = date.getSeconds();
                if(m<10){
                    m = '0'+m;
                }
                if(d<10){
                    d = '0'+d;
                }
                if(H<10){
                    H = '0'+H;
                }
                if(i<10){
                    i = '0'+i;
                }
                if(s<10){
                    s = '0'+s;
                }
                var t = Y+'-'+m+'-'+d+' '+H+':'+i;//+':'+s;
                return t; 
            }
方法2: Date对象添加原型链事件
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

2. 格式化日期转unix时间戳

//参数为格式化日期
var unixtime=function(strtime=false){ //不传入日期默认今日
                strtime = strtime.replace(/-/g,'/')  //解决低版本解释new Date('yyyy-mm-dd')这个对象出现NaN
                if(strtime){
                    var date = new Date(strtime);
                }else{
                    var date = new Date();
                }
                time1 = date.getTime();   //会精确到毫秒---长度为13位
                //time2 = date.valueOf(); //会精确到毫秒---长度为13位
                //time3 = Date.parse(date); //只能精确到秒,毫秒将用0来代替---长度为10位
                return time1;
            }

 

你可能感兴趣的:(前端杂项)