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

转载于:https://www.cnblogs.com/webchigan/p/6135617.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值