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


当前回答

假设您处理的是2014年[:-/.]06[:-//.]06或2014年06月[:-/./.]06日格式,那么您可以这样比较日期

var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';

parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false

如您所见,我们去掉分隔符,然后比较整数。

其他回答

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

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

注意-仅比较日期部分:

当我们在javascript中比较两个日期时。这需要数小时、数分钟和数秒的时间。。因此,如果我们只需要比较日期,这是一种方法:

var date1= new Date("01/01/2014").setHours(0,0,0,0);

var date2= new Date("01/01/2014").setHours(0,0,0,0);

现在:如果date1.valueOf()>date2.valueOf。

另一种比较两个日期的方法是通过toISOString()方法。这在与保存在字符串中的固定日期进行比较时特别有用,因为可以避免创建短时间对象。借助ISO 8601格式,您可以按字典方式比较这些字符串(至少在使用相同时区时)。

我不一定说它比使用时间对象或时间戳更好;只是将此作为另一种选择。这可能会失败,但我还没有发现:)

到目前为止,最简单的方法是从另一个日期中减去一个日期并比较结果。

var oDateOne=新日期();var oDateTwo=新日期();警报(oDateOne-oDateTwo==0);警报(oDateOne-oDateTwo<0);警报(oDateOne-oDateTwo>0);

使用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