时间戳,日期互转

一.日期转时间戳

1. 获取当前时间的时间戳

var date1 = new Date()
var timestamp1 = Date.parse(date1);
console.log(timestamp1);
//1511244766000 

2. 获取某个时间格式的时间戳

 var date2 = '2016-11-21 09:00:00'
 var timestamp2 = Date.parse(new Date(date2));
 console.log(timestamp2);
 //1479690000000

二.时间戳转日期

1.时间戳转各种格式日期

var timestamp3 = 1479690000000;
var newDate = new Date();
var a = newDate.setTime(timestamp3)
console.log(a);//1479690000000

console.log(newDate.toDateString());
 // Mon Nov 21 2016
console.log(newDate.toTimeString());
// 09:00:00 GMT+0800 (CST)
console.log(newDate.toJSON());
 // 2016-11-21T01:00:00.000Z
console.log(newDate.toISOString());
 // 2016-11-21T01:00:00.000Z
console.log(newDate.toGMTString());
 // Mon, 21 Nov 2016 01:00:00 GMT
console.log(newDate.toLocaleDateString());
 // 2016/11/21
console.log(newDate.toLocaleString());
 // 2016/11/21 上午9:00:00
 console.log(newDate.toLocaleTimeString());
 // 上午9:00:00
 console.log(newDate.toString());
 // Mon Nov 21 2016 09:00:00 GMT+0800 (CST)
 console.log(newDate.toTimeString());
// 09:00:00 GMT+0800 (CST)

2.通用函数

Date.prototype.format = function(format) {
       var date = {
              "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+)/i.test(format)) {
              format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
       }
       for (var k in date) {
              if (new RegExp("(" + k + ")").test(format)) {
                     format = format.replace(RegExp.$1, RegExp.$1.length == 1
                            ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
              }
       }
       return format;
}
 var timestamp3 = 1479690000000;
 var newDate = new Date();
 newDate.setTime(timestamp3)
 console.log(newDate.format('yyyy-MM-dd h:m:s'));
//2016-11-21 9:0:0

3.输出固定日期的函数

var abc = 1511191725638
function time(timeStamp) {
           var date = new Date();
           date.setTime(timeStamp);
           var y = date.getFullYear()
          //第一个月份是从0算起的,所以月份要加1
           var m = date.getMonth() + 1;
           m = m < 10 ? ('0' + m) : m;
           var d = date.getDate();
           d = d < 10 ? ('0' + d) : d;
           var h = date.getHours();
           h = h < 10 ? ('0' + h) : h;
           var min = date.getMinutes();
           var sec = date.getSeconds();
           min = min< 10 ? ('0' + min) : min;
           sec = sec < 10 ? ('0' + sec) : sec;
           return y + '-' + m + '-' + d+' '+h+':'+min+':'+sec;
       };
console.log(time(abc)); //2017-11-20 23:28:45
       

你可能感兴趣的:(时间戳,日期互转)