JavaScript Date的原型方法扩展

转自:http://www.nowamagic.net/librarys/veda/detail/561

在JavaScript开发中,经常需要对Date类型的对象进行各种验证或格式化,但是js并没有提供那么多的那么细的函数,所以只好自己去用 prototype 扩充了,下面是我自己实现的Date类型常用操作方法,你可以将它另存为date.js,然后在程序中调用即可。
view sourceprint?
001	/**
002	 * 日期时间脚本库方法列表:
003	 * (1)Date.isValiDate:日期合法性验证
004	 * (2)Date.isValiTime:时间合法性验证
005	 * (3)Date.isValiDateTime:日期和时间合法性验证
006	 * (4)Date.prototype.isLeapYear:判断是否闰年
007	 * (5)Date.prototype.format:日期格式化
008	 * (6)Date.stringToDate:字符串转成日期类型
009	 * (7)Date.daysBetween:计算两个日期的天数差
010	 * (8)Date.prototype.dateAdd:日期计算,支持正负数
011	 * (9)Date.prototype.dateDiff:比较日期差:比较两个时期相同的字段,返回相差值
012	 * (10)Date.prototype.toArray:把日期分割成数组:按数组序号分别为:年月日时分秒
013	 * (11)Date.prototype.datePart:取得日期数据信息
014	 */
015	
016	
017	/**
018	 * 日期合法性验证:判断dataStr是否符合formatStr指定的日期格式
019	 * 示例:
020	 * (1)alert(Date.isValiDate('2008-02-29','yyyy-MM-dd'));//true
021	 * (2)alert(Date.isValiDate('aaaa-58-29','yyyy-MM-dd'));//false
022	 * dateStr:必选,日期字符串
023	 * formatStr:可选,格式字符串,可选格式有:(1)yyyy-MM-dd(默认格式)或YYYY-MM-DD (2)yyyy/MM/dd或YYYY/MM/DD (3)MM-dd-yyyy或MM-DD-YYYY (4)MM/dd/yyyy或MM/DD/YYYY
024	 */
025	Date.isValiDate =function(dateStr, formatStr)
026	{
027	    if(!dateStr){
028	        returnfalse;
029	    }
030	    if(!formatStr){
031	        formatStr ="yyyy-MM-dd";//默认格式:yyyy-MM-dd
032	    }
033	    if(dateStr.length!=formatStr.length){
034	        returnfalse;
035	    }else{
036	        if(formatStr=="yyyy-MM-dd"||formatStr=="YYYY-MM-DD"){
037	            varr1=/^(((((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26]))))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-([0-2][0-9]))))|(d{2}(([02468][1235679])|([13579][01345789]))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-(([0-1][0-9])|(2[0-8]))))))$/;
038	            returnr1.test(dateStr);
039	        }elseif(formatStr=="yyyy/MM/dd"||formatStr=="YYYY/MM/DD"){
040	            varr2=/^(((((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26]))))/((((0[13578])|(1[02]))/(([0-2][0-9])|(3[01])))|(((0[469])|(11))/(([0-2][0-9])|(30)))|(02/([0-2][0-9]))))|(d{2}(([02468][1235679])|([13579][01345789]))/((((0[13578])|(1[02]))/(([0-2][0-9])|(3[01])))|(((0[469])|(11))/(([0-2][0-9])|(30)))|(02/(([0-1][0-9])|(2[0-8]))))))$/;
041	            returnr2.test(dateStr);
042	        }elseif(formatStr=="MM-dd-yyyy"||formatStr=="MM-DD-YYYY"){
043	            varr3=/^((((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-([0-2][0-9])))-(((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26])))))|(((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-(([0-1][0-9])|(2[0-8])))))-d{2}(([02468][1235679])|([13579][01345789])))$/;
044	            returnr3.test(dateStr);
045	        }elseif(formatStr=="MM/dd/yyyy"||formatStr=="MM/DD/YYYY"){
046	            varr4=/^((((((0[13578])|(1[02]))/(([0-2][0-9])|(3[01])))|(((0[469])|(11))/(([0-2][0-9])|(30)))|(02/([0-2][0-9])))/(((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26])))))|(((((0[13578])|(1[02]))/(([0-2][0-9])|(3[01])))|(((0[469])|(11))/(([0-2][0-9])|(30)))|(02/(([0-1][0-9])|(2[0-8])))))/d{2}(([02468][1235679])|([13579][01345789])))$/;
047	            returnr4.test(dateStr);
048	        }else{
049	            alert("日期格式不正确!");
050	            returnfalse;
051	        }
052	    }
053	    returnfalse;
054	}
055	
056	
057	/**
058	 * 时间合法性验证:判断timeStr是否符合formatStr指定的时间格式
059	 * 示例:
060	 * (1)alert(Date.isValiTime('23:59:59','hh:mm:ss'));//true
061	 * (2)alert(Date.isValiTime('24-68-89','hh:mm:ss'));//false
062	 * timeStr:必选,日期字符串
063	 * formatStr:可选,格式字符串,可选格式有:(1)hh:mm:ss(默认格式) (2)hh-mm-ss (3)hh/mm/ss
064	 */
065	Date.isValiTime =function(timeStr, formatStr)
066	{
067	    if(!timeStr){
068	        returnfalse;
069	    }
070	    if(!formatStr){
071	        formatStr ="hh:mm:ss";//默认格式:hh:mm:ss
072	    }
073	    if(timeStr.length!=formatStr.length){
074	        returnfalse;
075	    }else{
076	        if(formatStr=="hh:mm:ss"){
077	            varr1=/^(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9])$/;
078	            returnr1.test(timeStr);
079	        }elseif(formatStr=="hh-mm-ss"){
080	            varr2=/^(([0-1][0-9])|(2[0-3]))-([0-5][0-9])-([0-5][0-9])$/;
081	            returnr2.test(timeStr);
082	        }elseif(formatStr=="hh/mm/ss"){
083	            varr3=/^(([0-1][0-9])|(2[0-3]))/([0-5][0-9])/([0-5][0-9])$/;
084	            returnr3.test(timeStr);
085	        }else{
086	            alert("时间格式不正确!");
087	            returnfalse;
088	        }
089	    }
090	    returnfalse;
091	}
092	
093	
094	/**
095	 * 日期和时间合法性验证
096	 * 格式:yyyy-MM-dd hh:mm:ss
097	 */
098	Date.isValiDateTime =function(dateTimeStr)
099	{
100	    vardateTimeReg=/^(((((([02468][048])|([13579][26]))(00))|(d{2}(([02468][48])|([13579][26]))))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-([0-2][0-9]))))|(d{2}(([02468][1235679])|([13579][01345789]))-((((0[13578])|(1[02]))-(([0-2][0-9])|(3[01])))|(((0[469])|(11))-(([0-2][0-9])|(30)))|(02-(([0-1][0-9])|(2[0-8]))))))(s{1}(([0-1][0-9])|(2[0-3])):([0-5][0-9]):([0-5][0-9]))?$/
101	    returndateTimeReg.test(dateTimeStr);
102	}
103	
104	
105	/**
106	 * 判断闰年 :一般规律为:四年一闰,百年不闰,四百年再闰。
107	 */
108	Date.prototype.isLeapYear =function()
109	{
110	    return(this.getYear()%4==0&&((this.getYear()0!=0)||(this.getYear()%400==0)));
111	}
112	
113	
114	/**
115	 * 日期格式化:
116	 * formatStr:可选,格式字符串,默认格式:yyyy-MM-dd hh:mm:ss
117	 * 约定如下格式:
118	 * (1)YYYY/yyyy/YY/yy 表示年份
119	 * (2)MM/M 月份
120	 * (3)W/w 星期
121	 * (4)dd/DD/d/D 日期
122	 * (5)hh/HH/h/H 时间
123	 * (6)mm/m 分钟
124	 * (7)ss/SS/s/S 秒
125	 * (8)iii 毫秒
126	 */
127	Date.prototype.format =function(formatStr)
128	{
129	    varstr = formatStr;
130	    if(!formatStr){
131	        str ="yyyy-MM-dd hh:mm:ss";//默认格式
132	    }
133	    varWeek = ['日','一','二','三','四','五','六'];
134	     
135	    str=str.replace(/yyyy|YYYY/,this.getFullYear());
136	    str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));
137	     
138	    str=str.replace(/MM/,this.getMonth()>=9?(parseInt(this.getMonth())+1).toString():'0'+ (parseInt(this.getMonth())+1));
139	    str=str.replace(/M/g,(parseInt(this.getMonth())+1));
140	     
141	    str=str.replace(/w|W/g,Week[this.getDay()]);
142	     
143	    str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0'+ this.getDate());
144	    str=str.replace(/d|D/g,this.getDate());
145	     
146	    str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0'+ this.getHours());
147	    str=str.replace(/h|H/g,this.getHours());
148	    str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0'+ this.getMinutes());
149	    str=str.replace(/m/g,this.getMinutes());
150	     
151	    str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0'+ this.getSeconds());
152	    str=str.replace(/s|S/g,this.getSeconds());
153	     
154	    str=str.replace(/iii/g,this.getMilliseconds()<10?'00'+this.getMilliseconds():(this.getMilliseconds()<100?'0'+this.getMilliseconds():this.getMilliseconds()));
155	     
156	    returnstr;
157	}
158	
159	
160	/**
161	 * 字符串转成日期类型:
162	 * dateStr:必选,日期字符串,如果无法解析成日期类型,返回null
163	 * 格式:
164	 * (1)yyyy/MM/dd:IE和FF通用
165	 * (2)MM/dd/yyyy:IE和FF通用
166	 * (3)MM-dd-yyyy:仅IE
167	 * (4)yyyy-MM-dd:非IE,且时钟被解析在8点整
168	 */
169	Date.stringToDate =function(dateStr)
170	{
171	    if(!dateStr){
172	        alert("字符串无法解析为日期");
173	        returnnull;
174	    }else{
175	        if(Date.isValiDate(dateStr,"yyyy/MM/dd")||Date.isValiDate(dateStr,"MM/dd/yyyy")){
176	            returnnew Date(Date.parse(dateStr));
177	        }else{
178	            if((!-[1,])){//IE
179	                if(Date.isValiDate(dateStr,"MM-dd-yyyy")){
180	                    returnnew Date(Date.parse(dateStr));
181	                }else{
182	                    alert("字符串无法解析为日期");
183	                    returnnull;
184	                }
185	            }else{//非IE
186	                if(Date.isValiDate(dateStr,"yyyy-MM-dd")){
187	                    returnnew Date(Date.parse(dateStr));
188	                }else{
189	                    alert("字符串无法解析为日期");
190	                    returnnull;
191	                }
192	            }
193	        }
194	    }
195	    returnnull;
196	}
197	
198	
199	/**
200	 * 计算两个日期的天数差:
201	 * dateOne:必选,必须是Data类型的实例
202	 * dateTwo:必选,必须是Data类型的实例
203	 */
204	Date.daysBetween =function(dateOne,dateTwo)
205	{
206	    if((dateOneinstanceof Date)==false||(dateTwoinstanceof Date)==false){
207	        return0;
208	    }else{
209	        returnMath.abs(Math.floor((dateOne.getTime()-dateTwo.getTime())/1000/60/60/24));
210	    }
211	}
212	
213	
214	/**
215	 * 日期计算:支持负数,即可加可减,返回计算后的日期
216	 * num:必选,必须是数字,且正数是时期加,负数是日期减
217	 * field:可选,标识是在哪个字段上进行相加或相减,字段见如下的约定。无此参数时,默认为d
218	 * 约定如下格式:
219	 * (1)Y/y 年
220	
221	 * (2)M 月
222	 * (3)W/w 周
223	 * (4)D/d 日
224	 * (5)H/h 时
225	 * (6)m 分
226	 * (7)S/s 秒
227	 * (8)Q/q 季
228	 */
229	Date.prototype.dateAdd =function(num, field)
230	{
231	    if((!num)||isNaN(num)||parseInt(num)==0){
232	        returnthis;
233	    }
234	    if(!field){
235	        field ="d";
236	    }
237	    switch(field){
238	        case'Y':
239	        case'y':returnnew Date((this.getFullYear()+num),this.getMonth(), this.getDate(),this.getHours(), this.getMinutes(),this.getSeconds());break;
240	        case'Q':
241	        case'q':returnnew Date(this.getFullYear(), (this.getMonth()+num*3),this.getDate(), this.getHours(),this.getMinutes(), this.getSeconds());break;
242	        case'M':returnnew Date(this.getFullYear(),this.getMonth()+num, this.getDate(), this.getHours(),this.getMinutes(), this.getSeconds());break;
243	        case'W':
244	        case'w':returnnew Date(Date.parse(this) + ((86400000 * 7) * num));break;
245	        case'D':
246	        case'd':returnnew Date(Date.parse(this) + (86400000 * num));break;
247	        case'H':
248	        case'h':returnnew Date(Date.parse(this) + (3600000 * num));break;
249	        case'm':returnnew Date(Date.parse(this) + (60000 * num));break;
250	        case'S':
251	        case's':returnnew Date(Date.parse(this) + (1000 * num));break;
252	        default:return this;
253	    }
254	    returnthis;
255	}
256	
257	
258	/**
259	 * 比较日期差:比较两个时期相同的字段,返回相差值
260	 * dtEnd:必选,必须是Data类型的实例
261	 * field:可选,标识是在哪个字段上进行比较,字段见如下的约定。无此参数时,默认为d
262	 * 约定如下格式:
263	 * (1)Y/y 年
264	 * (2)M 月
265	 * (3)W/w 周
266	 * (4)D/d 日
267	 * (5)H/h 时
268	 * (6)m 分
269	 * (7)S/s 秒
270	 */
271	Date.prototype.dateDiff =function(dtEnd, field)
272	{
273	    vardtStart = this;
274	    if((dtEndinstanceof Date)==false){
275	        return0;
276	    }else{
277	        if(!field){
278	            field ="d";
279	        }
280	        switch(field){
281	            case'Y':
282	            case'y':returndtEnd.getFullYear() - dtStart.getFullYear();break;
283	            case'M':return(dtEnd.getMonth()+1)+((dtEnd.getFullYear()-dtStart.getFullYear())*12) - (dtStart.getMonth()+1);break;
284	            case'W':
285	            case'w':returnparseInt((dtEnd - dtStart) / (86400000 * 7));break;
286	            case'D':
287	            case'd':returnparseInt((dtEnd - dtStart) / 86400000);break;
288	            case'H':
289	            case'h':returnparseInt((dtEnd - dtStart) / 3600000);break;
290	            case'm':returnparseInt((dtEnd - dtStart) / 60000);break;
291	            case'S':
292	            case's':returnparseInt((dtEnd - dtStart) / 1000);break;
293	            default:return 0;
294	        }
295	        return0;
296	    }
297	}
298	
299	
300	/**
301	 * 把日期分割成数组:按数组序号分别为:年月日时分秒
302	 */
303	Date.prototype.toArray =function()
304	{
305	    varmyArray = new Array();
306	    myArray[0] =this.getFullYear();
307	    myArray[1] =this.getMonth();
308	    myArray[2] =this.getDate();
309	    myArray[3] =this.getHours();
310	    myArray[4] =this.getMinutes();
311	    myArray[5] =this.getSeconds();
312	    returnmyArray;
313	}
314	
315	
316	/**
317	 * 取得日期数据信息:
318	 * field:可选,标识是在哪个字段上进行比较,字段见如下的约定。无此参数时,默认为d
319	 * (1)Y/y 年
320	 * (2)M 月
321	 * (3)W/w 周
322	 * (4)D/d 日
323	 * (5)H/h 时
324	 * (6)m 分
325	 * (7)S/s 秒
326	 */
327	Date.prototype.datePart =function(field)
328	{
329	    if(!field){
330	        field ="d";
331	    }
332	    varWeek = ['日','一','二','三','四','五','六'];
333	    switch(field){
334	        case'Y' :
335	        case'y' :returnthis.getFullYear();break;
336	        case'M' :return(this.getMonth()+1);break;
337	        case'W' :
338	        case'w' :returnWeek[this.getDay()];break;
339	        case'D' :
340	        case'd' :returnthis.getDate();break;
341	        case'H' :
342	        case'h' :returnthis.getHours();break;
343	        case'm' :returnthis.getMinutes();break;
344	        case's' :returnthis.getSeconds();break;
345	        default:returnthis.getDate();
346	    }
347	    returnthis.getDate();
348	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值