如何检查新日期(“某日期”)能否正确解析? [英] How to check if new Date("some date") was able to parse correctly?

查看:133
本文介绍了如何检查新日期(“某日期”)能否正确解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,它应该试图解析一个给定的日期。如果失败,它将默认为当前日期:

I have the following code, which is supposed to try to parse a given date. If it fails, it defaults to the current date:

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

现在我使用isNaN()来测试是否能够解析正确的,例如检查新的Date()没有返回'无效的日期'。

Now i'm using isNaN() to test if it was able to parse correctly, eg to check that new Date() didn't return 'Invalid Date'.

这似乎在IE,FF和Chrome上工作正常,在野生动物园工作。例如,如果它尝试解析一个空字符串的日期,有时它认为是1970年,有时它认为这是一个无效的日期。以下是safari JS控制台的一个例子:

This seems to work fine on IE, FF, and Chrome, but doesn't work on safari. Eg if it tries to parse an empty string for the date, sometimes it think's it's 1970, and sometimes it thinks it's an invalid date. Here's an exerpt from the safari JS console:

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

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

Not sure whats happening here, thanks a lot

推荐答案

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

What Safari? Doesn't happen for me:

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

一般来说,虽然JavaScript Date 解析传统上是大部分未指定的,完全不可靠的。您不想依赖于用户输入值,因为它们将在浏览器,平台和语言环境中显示出不一致且通常不当的行为。编写自己的解析器通常更好(或使用现有的日期库之一,例如,fleegix)。

In general though JavaScript Date parsing is traditionally largely unspecified and totally unreliable. You don't want to rely on it for user-input values as it'll exhibit inconsistent and often inappropriate behaviour across browsers, platforms and locales. It's usually better to write your own parser (or use one of the existing date libraries, eg. fleegix's).

这篇关于如何检查新日期(“某日期”)能否正确解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆