JavaScript Date.parse() 和空日期
我正在尝试对日期列表进行排序,但我正在努力处理未一致处理的空日期。
所以我需要类似的东西:
var date = Date.parse(dateString);
if (!date) {
date = Date.MinValue;
}
但我正在努力寻找正确的语法。谢谢
更新:该错误原来是一个不同的问题。我已导入 Datejs 以便在项目的其他部分中使用,因此我没有意识到 Datejs 定义了一个 Date.parse()
方法,该方法覆盖了标准 JavaScript 方法。
不管怎样,事实证明 Datejs 有一个奇怪的错误,这意味着它不能正确处理以“A”开头的日期。所以实际上我的空日期排序正确,只是四月和八月日期与它们混淆了。
解决方法是使用 Datejs Date.parseExact
方法,该方法可让您提供特定的格式字符串,请参阅此处。
I'm trying to sort a list of dates, but I'm struggling with null dates which aren't being handled consistently.
So I need something like:
var date = Date.parse(dateString);
if (!date) {
date = Date.MinValue;
}
but I'm struggling to find the correct syntax. Thanks
Update: The bug turned out to be a different problem. I have Datejs imported for use in another part of the project, so I hadn't realised that Datejs defines a Date.parse()
method which was overriding the standard JavaScript method.
Anyway, it turns out that Datejs has a weird bug which means it doesn't handle dates beginning with "A" properly. So actually my null dates were being ordered correctly, it was just April and August dates were then being mixed up with them.
The fix is to use the Datejs Date.parseExact
method which lets you provide a specific format string, see here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
parse() 在不可能的解析上返回 NaN 那么怎么样?
parse() returns NaN on an impossible parse so how about just;
如果您确实正在寻找有效的 JS Date 对象(“空”或未设置,但因此默认为 1970 年 1 月 1 日)的比较来测试它是否错误 - 您可以使用:
这将创建一个设置为的 Date 对象从 Date() 开始计数的最小(第零个)时间戳...这相当于从未设置的 Date 对象。
If you're truly looking for comparison of a valid JS Date object (which is 'empty' or unset but therefore defaults Jan 01, 1970) to test whether it's falsey - you can use:
This will create a Date object that is set at the minimum (zero'th) timestamp from where Date() starts counting...which is equivilant to a Date object that has never been set.
您可以使用 isNaN(date) 来检查无效日期。您确定要使用“MinValue; from Date”吗?我在 chrome 上运行 js,但一直未定义。
You could use isNaN(date) to check for invalid date. Are you sure you want to use "MinValue; from Date? I was running the js on chrome and kept on getting undefined.