js 時間戳 日期格式化


一、 js獲取時間戳:
 
第一種方法:
var timestamp1 = Date.parse(new Date());
 
第二種方法:
var timestamp2 = new Date().valueOf();
 
第三種方法:
var timestamp3 = new Date().getTime();
 
alert(timestamp1);               //結果:1372751992000
alert(timestamp2);               //結果:1372751992066
alert(timestamp3);               //結果:1372751992066
 
備注:第一種獲取的時間戳是把毫秒改成000顯示,第二種和第三種是獲取了當前毫秒的時間戳。
 
  二、 時間戳格式化:
 
function formatDate(now) {
  var year = now.getFullYear(),
  month = now.getMonth() + 1,
  date = now.getDate(),
  hour = now.getHours(),
  minute = now.getMinutes(),
  second = now.getSeconds();
 
  return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
 
var d = new Date();
alert(formatDate(d));             //2016-12-12 12-12-12
 
三、 重寫Date原型鏈中的toString()方法
 很多時候,我們的頁面中會有許多關於時間的數據需要處理,這個時候改寫Date的原型方法顯然是一個很好的辦法,對吧?
Date.prototype.toString = function() {
return this.getFullYear()
+ "-" + (this.getMonth()>8?(this.getMonth()+1):"0"+(this.getMonth()+1))
+ "-" + (this.getDate()>9?this.getDate():"0"+this.getDate())
+ " " + (this.getHours()>9?this.getHours():"0"+this.getHours())
+ ":" + (this.getMinutes()>9?this.getMinutes():"0"+this.getMinutes())
+ ":" + (this.getSeconds()>9?this.getSeconds():"0"+this.getSeconds());
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM