Javascrip中對日期的解析、格式化簡直是混亂不堪,各類的坑,攻城獅們多當心。
1. 不要用 Date("yyyy-mm-dd") 構造函數解析字符串。
IE、firefox、safari 都不支持;
chrome 支持 Mozilla 標準,會調用 parse() 來解析。
因此這種用法不可用於跨瀏覽器的生產代碼。
2. Date.parse() 支持的格式:
各瀏覽器實現不同的,惟一能通用的格式是 ISO8601 標準,
即:yyyy-mm-ddThh:mm:ss 格式
但 chrome 下帶'T'的日期串會被認爲是UTC時區,在瀏覽器上執行時,會用瀏覽器時區作轉換,致使錯誤。
3. Date 的 month 是從0開始的!2月的值是 1!
最保險的方法是用 new Date(year,month-1,seconds); 方式構造指定時間對象。
Note that year should have 4-digits, and month starts with 0.
The date can be created given it’s components in the current time zone.
For this format there should be at least two first arguments, next ones are optional.
To create a date given it’s components in UTC time zone, use static method Date.UTC()
參考