Safari中的new Date()格式化坑


今天在測試的時候發現,在Chrome中的如下代碼:

new Date("2014-03-09");

在Safari中報錯invalid date。經過查閱資料找到類似的問答:

stackOverflow地址:http://stackoverflow.com/questions/4310953/invalid-date-in-safari

解釋與翻譯如下:

目前Safari可以支持的標准格式如下:

  • MM-dd-yyyy
  • yyyy/MM/dd
  • MM/dd/yyyy
  • MMMM dd, yyyy
  • MMM dd, yyyy

 DateJS 是一個很好的格式化非標准格式日期的庫。

關於Date日期標准,原文截取 ECMA-262 standard 內容進行說明,引文如下:

ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ Where the fields are as follows:

ECMAScript為基於ISO 8601擴展格式的日期時間定義了一個字符串交換格式。格式為YYYY-MM-DDTHH:mm:ss.sssZ,每個域的介紹如下:

  • YYYY is the decimal digits of the year in the Gregorian calendar. YYYY為格林威治時間年的十進制表達
  • ":" (hyphon) appears literally twice in the string. ":"字面上出現在兩個字符串之間
  • MM is the month of the year from 01 (January) to 12 (December). MM表示月份從01(一月)到12(十二月)
  • DD is the day of the month from 01 to 31. DD表示月份中的天數從01到31.
  • T "T" appears literally in the string, to indicate the beginning of the time element. T字面上出現在字符串中,表明時間元素的開始
  • HH is the number of complete hours that have passed since midnight as two decimal digits. HH表示從午夜算起,已經經過的完整兩位小時數字
  • : ":" (colon) appears literally twice in the string. ":"字面上出現在兩個字符串之間
  • mm is the number of complete minutes since the start of the hour as two decimal digits. mm表示從一個小時的開始算起,已經經過的完整兩位分鍾數字
  • ss is the number of complete seconds since the start of the minute as two decimal digits. ss表示從一分鍾的開始算起,已經經過的完整兩位秒數數字
  • . "." (dot) appears literally in the string. "."字面上出現在字符串里
  • sss is the number of complete milliseconds since the start of the second as three decimal digits. Both the "." and the milliseconds field may be omitted.  sss表示從一秒鍾的開始算起,已經經過的完整毫秒數,用三位數表示。該域可忽略不寫。
  • Z is the time zone offset specified as "Z" (for UTC) or either "+" or "-" followed by a time expression hh:mm Z特指時區偏移(特指UTC)或使用跟隨有時間表達式hh:mm 的"+"、"-"。如 +hh:mm

This format includes date-only forms: 這種格式可以只有日期,僅允許以下格式:

  • YYYY
  • YYYY-MM
  • YYYY-MM-DD

It also includes time-only forms with an optional time zone offset appended: 這種格式也可以只有時間,僅允許以下格式:

  • THH:mm
  • THH:mm:ss
  • THH:mm:ss.sss

Also included are "date-times" which may be any combination of the above. 同時也可以包含以上提到的日期或時間的組合。

所以可以看到,問題在於YYYY-MM-DD格式是包含在標准中的,只是Safari沒有實現。可以使用上文提到的DateJS對各種格式進行格式化以達到最大兼容性,舉例如下:

var myDate1 = Date.parseExact("29-11-2010", "dd-MM-yyyy");
var myDate2 = Date.parseExact("11-29-2010", "MM-dd-yyyy");
var myDate3 = Date.parseExact("2010-11-29", "yyyy-MM-dd");
var myDate4 = Date.parseExact("2010-29-11", "yyyy-dd-MM");

不過,如果僅是很少量的使用日期時間,個人認為無需打動干戈的去使用DateJS這種庫,簡單的進行正則匹配為safari可以識別的格式即可,如下:

new Date('2011-04-12'.replace(/-/g, "/"))

更多其他的變化,可以根據自己的業務需求進行代碼上的調整。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM