有人能提出一种方法来比较两个大于、小于和过去不使用JavaScript的日期的值吗?值将来自文本框。


当前回答

为了在众多现有选项中添加另一种可能性,您可以尝试:

if (date1.valueOf()==date2.valueOf()) .....

…这似乎对我有用。当然,你必须确保这两个日期都没有定义。。。

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....

通过这种方式,我们可以确保如果两者都未定义,或者。。。

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....

…如果你希望他们不平等。

其他回答

If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)

如果两个日期相同,则返回TRUE,否则返回FALSE

const compareDate = (dateVal1, dateVal2) => {
        if (dateVal1.valueOf() === dateVal2.valueOf()){
            return true;
        }
        else { return false;}
    }

比较两个日期的一种方法是使用dates.js库。

Date.compare(Date-date1,Date-date2)方法,返回一个数字,表示以下结果之一:

-1=日期1小于日期2。0=值相等。1=日期1大于日期2。

试试这个而比较日期应为iso格式“yyyy-MM-dd”如果要仅比较日期,请使用此datehelper

<a href="https://plnkr.co/edit/9N8ZcC?p=preview"> Live Demo</a>

我通常将日期作为时间戳(数字)存储在数据库中。

当我需要比较时,我只需在这些时间戳或

将其转换为Date Object,然后根据需要与><进行比较。

请注意,==或==无法正常工作,除非变量是同一日期对象的引用。

首先将这些Date对象转换为时间戳(数字),然后比较它们的相等性。


日期到时间戳

var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp

截至日期的时间戳

var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);

使用momentjs进行日期操作。


使用

isSameOrAfter()方法

moment('2010-10-20').isSameOrAfter('2010-10-20') //true;

使用isAfter()方法检查一个日期是否在另一个日期之后

moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true

使用isBefore()方法检查一个日期是否早于另一个日期。

moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false

使用isSame()方法检查一个日期与另一个日期是否相同

moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true