这篇文章主要是分享几个比较常用的时间方法:
时间格式化
获取前几天或后几天的日期
获取某月有多少天
获取星期几
获取两个日期时间差
//格式化日期
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') +'秒'
以上就是js中常用的时间方法有哪些的详细内容。