時間格式化
獲取前幾天或后幾天的日期
獲取某月有多少天
獲取星期幾
獲取兩個日期時間差
//格式化日期
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;
};
//獲取前幾天或后幾天的日期;正數(shù)表示前d天,負(fù)數(shù)表示后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āng)前時間是' + 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') +'秒'
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com