JS常用的时间方法总结

来源:互联网 发布:法律硕士有奖学金知乎 编辑:程序博客网 时间:2024/04/28 13:24
这篇文章主要是分享几个比较常用的时间方法:
  • 时间格式化
  • 获取前几天或后几天的日期
  • 获取某月有多少天
  • 获取星期几
  • 获取两个日期时间差


//格式化日期   

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') +'秒'


原创粉丝点击