js时间戳转换

 时间戳转换日期格式

//第一种
function formatDate(date) { 
     var year=date.getFullYear(); 
     var month=date.getMonth()+1; 
     var day=date.getDate(); 
     var hour=date.getHours(); 
     var minute=date.getMinutes(); 
     var second=date.getSeconds(); 
    //  return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
     return year + '-' + (String(month).length > 1 ? month : '0' + month) + '-' + 
     (String(day).length > 1 ? day : '0' + day) + ' ' + (String(hour).length > 1 ? hour : '0' + hour) + ':' + (String(minute).length > 1 ? minute : '0' + minute)
      + ':' + (String(second).length > 1 ? second : '0' + second)
} 
//如果记得时间戳是毫秒级的就需要*1000 不然就错了记得转换成整型
var d=new Date(1553547600000); //Tue Mar 26 2019 05:00:00 GMT+0800 (中国标准时间)
console.log(formatDate(d)) //2019-03-26 05:00:00


//第二种
function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y+M+D+h+m+s;
    }
    timestampToTime(1403058804);
    console.log(timestampToTime(1403058804));//2014-06-18 10:33:24

日期格式转

var date = new Date('2014-04-23 18:55:49:123');
    // 有三种方式获取
    var time1 = date.getTime();
    var time2 = date.valueOf();
    var time3 = Date.parse(date);
    console.log(time1);//1398250549123
    console.log(time2);//1398250549123
    console.log(time3);//1398250549000

换时间戳

你可能感兴趣的:(javascript)