javascript-時間戳
阿新 • • 發佈:2017-12-07
h+ this return date -m sos pla d+ length
1 // 獲取當前時間戳(以s為單位) 2 var timestamp = Date.parse(new Date()); 3 timestamp = timestamp / 1000; 4 console.log("當前時間戳為:" + timestamp); 5 6 7 8 // 獲取某個時間格式的時間戳 9 var stringTime = "2017-12-06 21:51:12"; 10 var timestamp2 = Date.parse(new Date(stringTime)); 11 timestamp2 = timestamp2 / 1000; 12 //2017-12-06 21:51:12的時間戳為:151256827213 console.log(stringTime + "的時間戳為:" + timestamp2); 14 15 var timestamp3 = 1512567397; 16 var newDate = new Date(); 17 newDate.setTime(timestamp3 * 1000); 18 // Wed Dec 06 2017 19 console.log(newDate.toDateString()); 20 // Wed, 06 Dec 2017 13:36:37 GMT 21 console.log(newDate.toGMTString()); 22 // 2017-12-06T13:36:37.000Z23 console.log(newDate.toISOString()); 24 // 2017-12-06T13:36:37.000Z 25 console.log(newDate.toJSON().replace(/:\d{1,2}$/,‘‘)); 26 // 2017-12-6 27 console.log(newDate.toLocaleDateString().replace(/\/+/g,‘-‘)); 28 // 2017/12/6 下午9:36:37 29 console.log(newDate.toLocaleString()); 30 // 下午9:36:37 31 console.log(newDate.toLocaleTimeString());32 // Wed Dec 06 2017 21:36:37 GMT+0800 (中國標準時間) 33 console.log(newDate.toString()); 34 // 21:36:37 GMT+0800 (中國標準時間) 35 console.log(newDate.toTimeString()); 36 // Wed, 06 Dec 2017 13:36:37 GMT 37 console.log(newDate.toUTCString());
1 var newDate = new Date(); 2 Date.prototype.format = function(format) { 3 var date = { 4 "M+": this.getMonth() + 1, 5 "d+": this.getDate(), 6 "h+": this.getHours(), 7 "m+": this.getMinutes(), 8 "s+": this.getSeconds(), 9 "q+": Math.floor((this.getMonth() + 3) / 3), 10 "S+": this.getMilliseconds() 11 }; 12 if (/(y+)/i.test(format)) { 13 format = format.replace(RegExp.$1, (this.getFullYear() + ‘‘).substr(4 - RegExp.$1.length)); 14 } 15 for (var k in date) { 16 if (new RegExp("(" + k + ")").test(format)) { 17 format = format.replace(RegExp.$1, RegExp.$1.length == 1? date[k] : ("00" + date[k]).substr(("" + date[k]).length)); 18 } 19 } 20 return format; 21 } 22 console.log(newDate.format(‘yyyy-MM-dd h:m:s‘));
javascript-時間戳