如何在忽略时间的同时判断两个日期是否相等?

时间:2019-04-25 18:14:58

标签: angular typescript

我想比较两个日期以查看它们是否相同,同时也忽略时间。

我尝试使用.setHours(0,0,0,0)方法将时间设置为中性,但是由于此错误,我无法使用.getTime()方法。 Property 'getTime' does not exist on type 'number'

我还研究了我不应该使用===,但是我不能首先克服getTime问题。

if (this.datelist.filter(x => new Date (x.sentDate).setHours(0,0,0,0).getTime() === this.searchQuery.getTime()).length == 0) {
    console.log("No matches");
}

3 个答案:

答案 0 :(得分:1)

我强烈建议 Moment.js 用于此类日期操作。 Moment.js变得如此简单

moment('2019-04-25').isSame('2019-04-25'); // true

在比较之前,有一些格式方法可以将日期转换为YYYY-MM-DD。

答案 1 :(得分:0)

Date#setHours方法已经返回了以毫秒为单位的时间,因此您不能在Date#getTime上使用Number方法。

由于Date#setHours方法已经返回了时间,因此您可以简单地忽略Date#getTime方法并与返回值进行比较。

if (this.datelist.every(x => new Date(x.sentDate).setHours(0,0,0,0) !== this.searchQuery.getTime())) {
    console.log("No matches");
}


为此,可以使用Array#every方法代替Array#fileter方法。

{{1}}

答案 2 :(得分:0)

您的问题是方法的串联。

当您拥有//java program to find minimum element in a sorted array rotated //about any pivot in O(log n) in worst case and O(1) in best case class ArrayRotateMinimum { public static void main(String str[]) { // initialize with your sorted rotated array here int array[] = { 9, 1, 2, 3, 4, 5, 6, 7, 8, }; System.out.println("Minimum element is: " + minimumElement(array)); } static int minimumElement(int array[]) { // variables to keep track of low and high indices int low, mid, high; // initializing variables with appropriate values low = 0; high = array.length - 1; while (low < high) { // mid is always defined to be the average of low and high mid = (low + high) / 2; if (array[low] > array[mid]) { // for eg if array is of the form [9,1,2,4,5], // then shift high to mid to reduce array size by half // while keeping minimum element between low and high high = mid; } else if (array[mid] > array[high]) { // this condition deals with the end case when the final two // elements in the array are of the form [9,1] during the // last iteration of the while loop if (low == mid) { return array[high]; } // for eg if array is of the form [4,5,9,1,2], // then shift low to mid to reduce array size by half // while keeping minimum element between low and high low = mid; } else { // the array has not been rotated at all // hence the first element happens to be the smallest element return array[low]; } } //return first element in case array size is just 1 return array[0]; } } 时,thing.methodA().methodB()将与methodB的任何返回值一起使用,在这种情况下,setHours从baseDate返回毫秒(以毫秒为单位)的时间,这是一个数字,并且没有methodA方法。

您的解决方案是在复制两个对象后在两个对象中使用setHours,即:

getTime()

还请注意,除非检查空值(使用if (this.datelist.filter(x => new Date (x.sentDate).setHours(0,0,0,0) === this.searchQuery.setHours(0,0,0,0)).length === 0) { console.log("nope!"); } ),否则在所有情况下都应始终使用'==='。

欢呼!