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());
}

posted @ 2016-12-05 21:38  独孤之路  阅读(17595)  评论(0编辑  收藏  举报