昨天遇到js时间比较的问题,期间想处处理不一样月份或不一样时间。待周末补充~函数
代码以下:测试
// 说明:JS时间Date格式化参数 // 参数:格式化字符串如:'yyyy-MM-dd HH:mm:ss' // 结果:如2016-06-01 10:09:00 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() }; var year = this.getFullYear(); var yearstr = year + ''; yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (yearstr + "").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; }
代码以下:this
// 说明:转换js的Date为: // 参数:JS的的Date // 返回:例如:1993年02月08日 转换后为 08FEB93 var parseDateStr = function(d) { var array = d.toDateString().split(' '); var str = array[2]+array[1]+array[3].substr(2,2); return str.toUpperCase() }
如图所示:spa
代码以下:prototype
// 说明:两个时间相减 // 参数:JS的Date类型,或者 string 类型,格式为:yyyy-MM-dd HH:mm:ss // 返回: date1-date2的秒数 var substractDate = function(date1, date2){ var type1 = typeof date1; var type2 = typeof date2; if (type1 == 'string') { date1 = new Date(date1); } if (type2 == 'string') { date2 = new Date(date2); } return (date1 - date2) / 1000; }
测试结果,如图所示:code
两个日期相差的月份,不能简单的以1个月有多少天来计算,由于有的月份有30天,有的有31天。因此是下面这种计算方式。相差的年份的计算能够参考下面这种方式。orm
代码以下:blog
var getDiffMonths = function(date1, date2) { if (!date1 instanceof Date){ console.error('param date1 is not Date'); } if (!date2 instanceof Date){ console.error('param date2 is not Date'); } var months1 = date1.getFullYear() * 12 + date1.getMonth(); var months2 = date2.getFullYear() * 12 + date2.getMonth(); return months1 - months2; }
测试结果,如图所示:字符串
代码以下:get
// 说明:添加天数 // 参数:天数 好比40天 // 结果:好比日期:2016-16-13,加40天,结果为:2016-07-23 Date.prototype.addDays = function(days) { var date = new Date(this); date.setDate(date.getDate() + days); return date; }