JS對日期操作封裝代碼實例
更新時間:2019年11月08日 11:37:40 作者:coding++
這篇文章主要介紹了JS對日期操作封裝代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了JS對日期操作封裝代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
格式化日期:
/** * 格式化日期 * @param fmt 例如:yyyy-MM-dd 等 * @returns {*} * @constructor */ Date.prototype.Format = function (fmt) { //author: meizz 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.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; };
得到日期年月日等 加數(shù)字后的日期:
/** * 得到日期年月日等 加數(shù)字后的日期 * @param interval 指定類型 例如 y:代表年 * @param number 需要增加 || 減少的 值 * @param fmt 格式化日期 可選參數(shù) 默認:Thu Oct 24 2019 16:57:12 GMT+0800 (中國標準時間) 格式 * @returns {Date} */ Date.prototype.dateAdd = function(interval,number,fmt) { var d = this; var k={'y':'FullYear', 'q':'Month', 'm':'Month', 'w':'Date', 'd':'Date', 'h':'Hours', 'n':'Minutes', 's':'Seconds', 'ms':'MilliSeconds'}; var n={'q':3, 'w':7}; eval('d.set'+k[interval]+'(d.get'+k[interval]+'()+'+((n[interval]||1)*number)+')'); if (fmt){ return d.Format(fmt); } return d; };
計算兩日期相差的日期年月日等:
/** * 計算兩日期相差的日期年月日等 * @param interval 指定查看的類型 例如:y:代表年 * @param objDate2 objDate2 < this = 負數(shù) * @returns {*} */ Date.prototype.dateDiff = function(interval,objDate2) { var d=this, i={}, t=d.getTime(), t2=objDate2.getTime(); i['y']=objDate2.getFullYear()-d.getFullYear(); i['q']=i['y']*4+Math.floor(objDate2.getMonth()/4)-Math.floor(d.getMonth()/4); i['m']=i['y']*12+objDate2.getMonth()-d.getMonth(); i['ms']=objDate2.getTime()-d.getTime(); i['w']=Math.floor((t2+345600000)/(604800000))-Math.floor((t+345600000)/(604800000)); i['d']=Math.floor(t2/86400000)-Math.floor(t/86400000); i['h']=Math.floor(t2/3600000)-Math.floor(t/3600000); i['n']=Math.floor(t2/60000)-Math.floor(t/60000); i['s']=Math.floor(t2/1000)-Math.floor(t/1000); return i[interval]; };
演示:
console.log(new Date('2019-10-23').dateAdd('y',1,'yyyy-MM-dd')) 結(jié)果為:2020-10-23
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
js常用方法、檢查是否有特殊字符串、倒序截取字符串操作完整示例
這篇文章主要介紹了js常用方法、檢查是否有特殊字符串、倒序截取字符串操作,結(jié)合完整實例形式分析了JavaScript字符串轉(zhuǎn)換、檢測、倒序、截取等相關操作技巧,需要的朋友可以參考下2020-01-01Bootstrap下拉菜單更改為懸停(hover)觸發(fā)的方法
這篇文章主要為大家詳細介紹了Bootstrap下拉菜單更改為懸停(hover)觸發(fā)的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05