JavaScript Date.parse() 和空日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3263991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:56:48  来源:igfitidea点击:

JavaScript Date.parse() and null dates

javascriptdatetimecomparisonnull

提问by fearofawhackplanet

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 Datejsimported 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.

更新:这个错误原来是一个不同的问题。我导入了Datejs用于项目的另一部分,所以我没有意识到 Datejs 定义了一个Date.parse()覆盖标准 JavaScript 方法的方法。

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.

无论如何,事实证明 Datejs 有一个奇怪的错误,这意味着它不能正确处理以“A”开头的日期。所以实际上我的空日期被正确排序,只是四月和八月的日期与它们混淆了。

The fix is to use the Datejs Date.parseExactmethod which lets you provide a specific format string, see here.

解决方法是使用 DatejsDate.parseExact方法,该方法可让您提供特定的格式字符串,请参见此处

回答by Alex K.

parse() returns NaN on an impossible parse so how about just;

parse() 在不可能的解析上返回 NaN,所以怎么样?

 var date = Date.parse(dateString) || 0;

回答by Ravindra

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.

您可以使用 isNaN(date) 检查无效日期。您确定要使用“MinValue; from Date?我在 chrome 上运行 js 并一直未定义。

回答by Michael Angstadt

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:

如果您真的要比较有效的 JS 日期对象(“空”或未设置,但因此默认为 1970 年 1 月 1 日)来测试它是否为假 - 您可以使用:

var null_date = new Date(0);

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.

这将创建一个 Date 对象,该对象设置为 Date() 开始计数的最小(第零个)时间戳......这相当于从未设置过的 Date 对象。