您的位置:首页 > Web前端 > JavaScript

js日期字符串比较大小

2014-05-02 17:04 260 查看
今天遇到了大问题,确切来说并不大,只是比较麻烦——js日期字符串的比较大小。
1,字符串类型的日期能否比较大小,答案是能


这只是在chrome浏览器中结果,其他浏览器,还需要各位自己亲自实验下 如何转换成字符串或格式话?请看下面这个函数
//格式化日期,
function formatDate(date,format){
var paddNum = function(num){
num += "";
return num.replace(/^(\d)$/,"0$1");
};
//指定格式字符
var cfg = {
'yyyy': date.getFullYear(), //年 : 4位
'yy' : date.getFullYear().toString().substring(2),//年 : 2位
'M'  : date.getMonth() + 1,  //月 : 如果1位的时候不补0
'MM' : paddNum(date.getMonth() + 1), //月 : 如果1位的时候补0
'd' : date.getDate(),  //日 : 如果1位的时候不补0
'dd' : paddNum(date.getDate()),//日 : 如果1位的时候补0
'hh' : date.getHours(),  //时
'mm' : date.getMinutes(), //分
'ss' : date.getSeconds() //秒
};
format || (format = "yyyy-MM-dd");
return format.replace(/([a-z])(\1)*/ig,function(m){
return cfg[m];});
}
2,通用的解法,转换成日期格式(扒自其他网站)
var time1 = new Date(d1.replace("-", "/").replace("-", "/"));
var time2 = new Date(d2.replace("-", "/").replace("-", "/"));
if(time1 > time2)
{
alert("time1 大于 time2");
}
3,使用解析成一个number对象,表示:解析一个包含日期的字符串,并返回该日期与 1970 年 1 月 1 日午夜之间所间隔的毫秒数)
/*
Date.prase("2014/05/02");
测试 IE和FF   用什么格式显示如何!
*/
<script language="JavaScript">
alert("Date: "+Date.parse("2000-01-01"))
// On IE and Mozilla: "Date: NaN"
alert("Date: "+Date.parse("01-01-2000"))
// On IE: "Date: 946681200000"
// On Mozilla: "Date: NaN"
alert("Date: "+Date.parse("01/01/2000"))
alert("Date: "+Date.parse("2000/01/01"))
// On IE and Mozilla: "Date: 946681200000"
</script>
详细,可以参考http://hi.baidu.com/wanghui320/item/e942e543d9bb42a961d7b9d2的内容,很详细
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息