JS常用的时间方法总结

这篇文章主要是分享几个比较常用的时间方法:
  • 时间格式化
  • 获取前几天或后几天的日期
  • 获取某月有多少天
  • 获取星期几
  • 获取两个日期时间差


//格式化日期   

Date.prototype.Format = function(fmt) {   

  var o = {   

    "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+)/.test(fmt)) {   

    fmt = fmt.replace(RegExp.$<span class="hljs-number">1</span>, (<span class="hljs-keyword">this</span>.getFullYear() + <span class="hljs-string">""</span>).substr(<span class="hljs-number">4</span> - RegExp.$1.length));   

  };   

  for(var k in o) {   

    if(new RegExp("(" + k + ")").test(fmt)) {   

       fmt = fmt.replace(RegExp.$<span class="hljs-number">1</span>, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));   

    }   

  };   

   return fmt; 

};   

//获取前几天或后几天的日期;正数表示前d天,负数表示后d天   

Date.prototype.getWitchDate=function(d){   

  if(/(\d)/.test(d)){   

    d=this.getDate()+d;   

    this.setDate(d)   

  };   

  return this;   

};   

//获取某月有多少天   

Date.prototype.getMonthTotalDay=function(){   

  this.setDate(32);   

  return 32-this.getDate();   

};   

//获取周几   

Date.prototype.getWeek=function(d){   

  var week=['星期一','星期二','星期三','星期四','星期五','星期六','星期天'];   

  if(typeof d !== 'undefined'){   

    return week[parseInt(d)%7];   

  };   

  return week[this.getDay()]; };

//获取两个日期的时间差,单位秒   

Date.prototype.getDateSecond=function(d){   

  if(typeof d === 'string'){   

    d=new Date(d);   

  }   

  var t1=this.getTime();   

  var t2=d.getTime();   

  return Math.floor(Math.abs(t1-t2)/1000);   

};

用法:

var h = '当前时间是' + d.Format('yyyy-MM-dd hh:mm:ss')+'</br>';

h += '3天前是' + d.getWitchDate(-3).Format('yyyy-MM-dd hh:mm:ss')+'</br>';   

h += '9月份有' + d.getMonthTotalDay()+'天</br>';   

h += '今天是' + d.getWeek()+'</br>'

h += '今天距离2016年9月15日相差' +  d.getDateSecond('2016/9/15') +'秒'


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值