最近看了一些关于面向对象的知识,最近工作中在做统计查询的时候需要用到本月、近三个月、今年的日期范围,所以下面用用面向对象的思想写了一个获取日期的插件,大家可以借鉴使用。
直接通过new datehelp就可以调用了
var mydate = new datehelp({date:'2015-02-01',//从此日期开始计算format:'yyyy/mm/dd'});mydate.getthismonth();mydate.getthreemonth();mydate.getthisyear();
datehelp.js插件
/** * 通过调用可以获取本月,近三个月,今年的日期 * @param obj * @constructor */function datehelp(obj) { /*var obj = { date:'2015-02-01',//从此日期开始计算 type:'month',//以年月日向前计算:年(year),月(month),日(day) value:'14',//向前计算的数值,年月日 format:'yyyy/mm/dd'//日期格式 }*/ this.date = obj.date; this.type = obj.type; this.value = obj.value == undefined ? obj.value : 0; this.format = obj.format == undefined ? obj.format: 'yyyy/mm/dd'; //日期和非日期格式获取年月日 if (this.date instanceof date){ //处理传进来的是日期函数的 this.year = this.date.getfullyear(); this.month = this.date.getmonth()+1; this.day = this.date.getdate(); }else{ //处理传入的是非日期函数的 this.year = this.date.substr(0, 4); this.month = this.date.substr(5, 2); this.day = this.date.substr(8, 2); }}datehelp.prototype.beforedate = function(type, value){ var _type = type || this.type, _value = value || this.value, _year = this.year, _month = this.month, _day = this.day; if (_type == 'year' || _type == '年'){ _year -= _value; }else if (_type == 'month' || _type == '月'){ _year -= parseint(_value / 12); _month -= _value % 12; if(_month <= 0){ _year -= 1; _month += 12; } }else if (_type == 'day' || _type == '日'){ }else { } var date = new date(_year, _month - 1, _day) return this.formatdate(date, this.format);}datehelp.prototype.formatdate = function(date,fmt){ var o = { m+ : date.getmonth()+1, //月份 d+ : date.getdate(), //日 h+ : date.gethours(), //小时 m+ : date.getminutes(), //分 s+ : date.getseconds(), //秒 q+ : math.floor((date.getmonth()+3)/3), //季度 s : date.getmilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) fmt=fmt.replace(regexp.$1, (date.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;}datehelp.prototype.getthismonth = function() { var first = new date(this.year, this.month - 1); var last = new date(this.year, this.month, 0); return this.formatdate(first, this.format) + - + this.formatdate(last, this.format);}datehelp.prototype.getthreemonth = function() { return this.beforedate('month', 3) + - + this.beforedate('day', 0);}datehelp.prototype.getthisyear = function() { var first = new date(this.year, 0, 1); var last = new date(this.year, 11, 31); return this.formatdate(first, this.format) + - + this.formatdate(last, this.format);}/*//示例var mydate = new datehelp({ date:'2015-02-01',//从此日期开始计算 format:'yyyy/mm/dd'});console.log(mydate.getthismonth());console.log(mydate.getthreemonth());console.log(mydate.getthisyear());*/
html测试代码
希望本文所述对大家学习javascript程序设计有所帮助。