今天遇到了大問題,確切來說並不大,只是比較麻煩——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的內容,很詳細