编程爱好者之家

javascript时间戳和日期字符串相互转换

2018-02-26 10:53:21 245

// 获取当前时间戳(以s为单位)
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000;
//当前时间戳为:1519613380
console.log("当前时间戳为:" + timestamp);

// 获取某个时间格式的时间戳
var stringTime = "2018-02-26 10:50:11";
var timestamp2 = Date.parse(new Date(stringTime));
timestamp2 = timestamp2 / 1000;
//2018-02-26 10:50:11的时间戳为:1519613411
console.log(stringTime + "的时间戳为:" + timestamp2);

// 将当前时间换成时间格式字符串
var timestamp3 = 1519613411;
var newDate = new Date();
newDate.setTime(timestamp3 * 1000);
// Mon Feb 26 2018 
console.log(newDate.toDateString());
// Mon, 26 Feb 2018 02:50:11 GMT
console.log(newDate.toGMTString());
// 2018-02-26T02:50:11.000Z
console.log(newDate.toISOString());
// 2018-02-26T02:50:11.000Z
console.log(newDate.toJSON());
// 2018/2/26 
console.log(newDate.toLocaleDateString());
// 2018/2/26 上午10:50:11
console.log(newDate.toLocaleString());
// 上午10:50:11 
console.log(newDate.toLocaleTimeString());
// Mon Feb 26 2018 10:50:11 GMT+0800 (标准时间)
console.log(newDate.toString());
// 10:50:11 GMT+0800 (标准时间) 
console.log(newDate.toTimeString());
// Mon, 26 Feb 2018 02:50:11 GMT
console.log(newDate.toUTCString());

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;
}
console.log(newDate.format('yyyy-MM-dd h:m:s'));
//2018-02-26 10:50:11


同类文章