簡體   English   中英

在JavaScript中使用> =運算符的日期比較錯誤

[英]Date comparison error using >= operator in Javascript

嗨,我正在嘗試比較與今天或將來有關的對象的日期。 如果是昨天和以前,則不應該顯示。 那就是條件。

當我將今天的日期與new Date()進行比較時,該條件應該為true,但它返回的是false,因此,這些條件將無法正常運行。 此代碼有什么問題?

data = [
   '0': {type: "recare", value: "Hello", date: "2018-06-05", ... },
   '1': {type: "tocall", value: "World", date: "2018-06-13", ... },
   '2': {type: "recare", value: "People", ...}
];

console.log(new Date(data[0].date) >= new Date())
//returns: false

    console.log(new Date(data[1].date) >= new Date())
//returns: true

為什么返回假? 對於第二個對象,它會返回true,因為與今天(06-05)相比,將來是06-13

因為新的Date()也包括當前時間部分。 您可以使用新的Date()。setHours(0,0,0,0)進行修復。

 data = [ {type: "recare", value: "Hello", date: "2018-06-06" }, {type: "tocall", value: "World", date: "2018-06-13" }, {type: "recare", value: "People"} ]; console.log(new Date(data[0].date) >= new Date().setHours(0,0,0,0)) //returns: false console.log(new Date(data[1].date) >= new Date().setHours(0,0,0,0)) //returns: true 

如果您嘗試記錄前兩個值,則會看到不同的輸出

 const data = [ { type: 'recare', value: 'Hello', date: '2018-06-05' }, { type: 'tocall', value: 'World', date: '2018-06-13' }, { type: 'recare', value: 'People' }, ]; // this will evaulate to the date since the day started 00:00 console.log(new Date(data[0].date)); // this will evaulate to the current time console.log(new Date()) ; // so new Date() is >= than new Date(data[0].data) ; // so this will be false console.log(new Date(data[0].date) >= new Date()); 

您可以將2個日期與其他道具(例如getHoursgetMonth)進行比較,還有許多其他道具可以使用

了解有關日期對象日期Javascript MDN的更多信息

@Sam ,嘗試下面的代碼。

var data = [
   {type: "recare", value: "Hello", date: "2018-06-05" },
   {type: "tocall", value: "World", date: "2018-06-13" },
   {type: "recare", value: "People", date: "2018-06-06"}
]

var date = new Date()
console.log(date)
var year = date.getFullYear() 
var month = date.getMonth() 
var day = date.getDate()

console.log(year, month, day)

var today = new Date(year, month, day)
console.log(new Date(data[0].date) >= today) // returns false

console.log(new Date(data[0].date) == today); //returns: true

console.log(new Date(data[1].date) > today); //returns: true

輸出:

Tue Jun 05 2018 22:41:27 GMT+0200 (CEST)
2018 5 5
true
false
true

請專注於以下兩行代碼,因為上面提供的解決方案基於此。

✓以下2條陳述彼此等同

console.log(new Date("2018-08-07"));
console.log(new Date(2018, 7, 7)); // month ranges from 0-11 in call to Date() contructor

輸出:

Tue Aug 07 2018 02:00:00 GMT+0200 (CEST)
Tue Aug 07 2018 00:00:00 GMT+0200 (CEST)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM