近期做了一个POC,需要在浏览器端做一些日期的处理工作,除去其中跟公司产品相关的部分,其它的代码还是比较通用的,主要有两个功能:
- 根据一个Date对象获取相对应的特殊时间点,比如一天、一个月或者一年的起止时间;
- 在一个Date对象上加减相应的时间值
js 代码
- /**
- * This file is a Date extension which can handle specified moments
- *
- /**
- * set the Date object to a specific local moment
- * @param {enum} iMoment the specific moment, can reference those extened properties of Date.
- */
- Date.prototype.setToLocalMoment=function(iMoment)
- {
- switch (iMoment) {
- case Date.MOMENT_DATE_START:
- this.setHours(0,0,0,0);
- break;
- case Date.MOMENT_DATE_END:
- this.setHours(23,59,59,999);
- break;
- case Date.MOMENT_MONTH_START:
- this.setHours(0,0,0,0);
- this.setDate(1);
- break;
- case Date.MOMENT_MONTH_END:
- this.setHours(23,59,59,999);
- //can not get the last day of a month directly,
- //so set to the first day in next month, and minus one day.
- //numDate is start from 1, so 0 means the last day before 1st
- this.setMonth(this.getMonth()+1, 0);
- break;
- case Date.MOMENT_YEAR_START:
- this.setHours(0,0,0,0);
- //numMonth is start from 0, to 11, but numDate is from 1 to 31, weird
- this.setMonth(0, 1);
- break;
- case Date.MOMENT_YEAR_END:
- this.setHours(23,59,59,999);
- this.setMonth(11, 31);
- break;
- default:
- }
- }
- /**
- * plus the specific values to this Date object
- * All parameters are optional, if one of them is positive, it's plused, otherwise, it's minused.
- * @param {int} iYear
- * @param {int} iMonth
- * @param {int} iDate
- * @param {int} iHours
- * @param {int} iMinutes
- * @param {int} iSeconds
- * @param {int} iMilliseconds
- */
- Date.prototype.plus=function(iYear,iMonth,iDate,iHours,iMinutes,iSeconds,iMs)
- {
- var ilYear=this.getFullYear(); ilYear+=iYear?iYear:0;
- var ilMonth=this.getMonth(); ilMonth+=iMonth?iMonth:0;
- var ilDate=this.getDate(); ilDate+=iDate?iDate:0;
- var ilHours=this.getHours(); ilHours+=iHours?iHours:0;
- var ilMinutes=this.getMinutes(); ilMinutes+=iMinutes?iMinutes:0;
- var ilSeconds=this.getSeconds(); ilSeconds+=iSeconds?iSeconds:0;
- var ilMs=this.getMilliseconds(); ilMs+=iMs?iMs:0;
- var date=new Date();
- date.setFullYear(ilYear, ilMonth, ilDate);
- date.setHours(ilHours,ilMinutes, ilSeconds,ilMs);
- return date;
- }
- Date.prototype.minus=function(iYear,iMonth,iDate,iHours,iMinutes,iSeconds,iMs)
- {
- return this.plus(-iYear,-iMonth,-iDate,-iHours,-iMinutes,-iSeconds,-iMs);
- }
- /**
- * extened properties of Date: to define a set of special moment
- */
- Date.MOMENT_DATE_START=100;
- Date.MOMENT_DATE_END=101;
- Date.MOMENT_MONTH_START=110;
- Date.MOMENT_MONTH_END=111;
- Date.MOMENT_YEAR_START=120;
- Date.MOMENT_YEAR_END=121;