代码之家  ›  专栏  ›  技术社区  ›  Chris

如何检查新日期(“某个日期”)是否能够正确解析?

  •  2
  • Chris  · 技术社区  · 14 年前

    我有下面的代码,它应该尝试解析给定的日期。如果失败,则默认为当前日期:

    var date = new Date(textbox.value); // Try to parse
    if (isNaN(date)) date = new Date(); // Default to current
    

    现在我使用isNaN()测试它是否能够正确解析,例如检查new Date()是否返回“Invalid Date”。

    这在IE、FF和Chrome上似乎可以正常工作,但在safari上不起作用。例如,如果它试图解析日期的空字符串,有时会认为是1970年,有时会认为是无效日期。以下是来自safari JS控制台的练习:

    a=new Date("")  <-- This thinks it's 1970 for some reason
    Thu Jan 01 1970 11:00:00 GMT+1100 (AUS Eastern Daylight Time)
    
    b=new Date("abc") <-- Fails of course, which is good
    Invalid Date
    
    c=new Date("") <-- Why does this fail now, whereas it thought it was 1970 before?
    Invalid Date
    
    isNaN(a)  <-- Why is it successfully parsing an empty string for a date?
    false
    
    isNaN(b)  <-- Fair enough
    true
    
    isNaN(c)  <-- This is what i'd expect, but why is it different now?
    true
    

    不知道这里发生了什么,非常感谢

    1 回复  |  直到 14 年前
        1
  •  4
  •   bobince    14 年前

    什么狩猎?不会发生在我身上:

    > a= new Date('')
    Invalid Date
    > isNaN(a)
    true
    

    在Safari 4.0(任一操作系统)上。

    Date 传统上,解析在很大程度上是不确定的,而且完全不可靠。您不希望依赖它来获取用户输入值,因为它会在浏览器、平台和区域设置之间表现出不一致且通常不适当的行为。通常最好编写自己的解析器(或者使用现有的日期库之一,例如fleegix的)。