1.比较常用的方法,但繁琐:
主要使用Date的构造方法:Date(int year , int month , int day)
- <script>
- var str1 = "2009-8-9";
- var arr1 = str1.split("-");
- var date1 = new Date(arr1[0],parseInt(arr1[1])-1,arr1[2]);
- var str2 = "2009-8-4";
- var arr2 = str2.split("-");
- var date2 = new Date(arr2[0],parseInt(arr2[1])-1,arr2[2]);
- alert(date1>date2);//true
- </script>
2.简便方法:
- var str = "2005-12-15";
- var d = new Date(str.replace(/-/g, "/"));
- /-/g是js的正则表达式,匹配划线的
- re = /pattern/[flags]
- 用 "/ " 字符分隔模式
- g (全文查找出现的所有 pattern)
- i (忽略大小写)
- m (多行查找)
Example:
- <script>
- var s = "2010-09-11";
- var s1 = "2010-09-12";
- var d = new Date(s.replace(/-/g,"/"));
- var d1 = new Date(s1.replace(/-/g,"/"));
- var m = (d1.getTime()-d.getTime())/(1000*60*60);
- alert(m); //24
- </script>
JS比较时间:
- <script language="JavaScript">
- //时间对比函数,如果a>b返回1,如果a<b返回-1,相等返回0
- function comptime(a,b)
- {
- var dateA = new Date("1900/1/1 " + a);
- var dateB = new Date("1900/1/1 " + b);
- if(isNaN(dateA) || isNaN(dateB)) return null;
- if(dateA > dateB) return 1;
- if(dateA < dateB) return -1;
- return 0;
- }
- var timeStart = "3:20";
- var timeEnd = "2:11";
- if(comptime(timeStart,timeEnd) != -1)
- alert("开始时间必须小于结束时间!");
- </script>