DIV CSS 佈局教程網

JS 將 yyyy-MM-dd 格式的字符串日期轉為 Date 示例
編輯:JavaScript綜合知識     

本文記錄了一個日期格式轉換的問題:在把表單中的日期以 JSON 方式傳到後台時,Date.parse(str) 函數在 Firefox 下報錯返回 NaN。有類似情況的朋友可以參考。

問題根源在於 Date.parse() 對日期格式有要求。我們先來了解 JS 中日期對象的構造方式:

創建日期對象:var objDate = new Date([arguments list]);

參數形式有以下 5 種:

new Date("month dd,yyyy hh:mm:ss"); new Date("month dd,yyyy"); new Date(yyyy,mth,dd,hh,mm,ss); new Date(yyyy,mth,dd); new Date(ms);

說明:month 用英文月份名(January 到 December);mth 用整數表示月份(0 到 11);dd 為月份的某一天(1 到 31);yyyy 為四位年份;hh、mm、ss 分別為時、分、秒;ms 為相對於 1970 年 1 月 1 日的毫秒數。

實踐中發現,Javascript 的日期構造還支持 new Date("yyyy/MM/dd") 這種寫法,這樣配合正則表達式就能很方便地轉換字符串日期了。

測試代碼:

<script type="text/javascript"> document.write("<br/>" + new Date("February 3,2009")); document.write("<br/>" + new Date("February 3,2009 10:52:03")); document.write("<br/>" + new Date(2009,1,3)); document.write("<br/>" + new Date(2009,1,3,10,52,03)); document.write("<br/>" + new Date(Date.parse("February 3,2009"))); document.write("<br/>" + new Date(Date.parse("February 3,2009 10:52:03"))); document.write("<br/>" + new Date(Date.parse(2009,1,3))); //Output: NAN document.write("<br/>" + new Date(Date.parse("2009/02/03"))); document.write("<br/>" + new Date("2009/02/03")); document.write("<br/>" + new Date("2009/02/03 11:12:13")); document.write("<br/>" + new Date("2009-02-03")); //Output: NAN </script>

由此可見,帶橫杠的 "2009-02-03" 在部分環境下會返回 NaN,而斜杠格式 "2009/02/03" 則能被正確解析。因此,解決思路就是把橫杠替換成斜杠:

<script> window.onload=function(){ var dependedVal="2005-3-4"; //根據日期字符串轉換成日期 var regEx = new RegExp("-","gi"); dependedVal=dependedVal.replace(regEx,"/"); alert(dependedVal) //parse 需要 2005/3/4 這種格式 var milliseconds=Date.parse(dependedVal); alert(milliseconds) var dependedDate=new Date(); dependedDate.setTime(milliseconds); var now = new Date(); //注意括號,優先級問題 alert("相隔年數:"+(now.getFullYear() - dependedDate.getFullYear())); } </script>

補充一點:日期在瀏覽器和服務器之間傳輸時,最好通過毫秒值(時間戳)來傳,否則容易因格式差異而報錯。總結來說,把 "yyyy-MM-dd" 中的橫杠全局替換為斜杠,再交給 Date.parse 或 new Date,就能穩定地得到正確的日期對象。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved