您好我试图比较与今天或未来相关的对象的日期。如果是从昨天开始,那么它就不应该出现了。这就是条件。
当我将今天的日期与new Date()
进行比较时,该条件应该为真,但它会返回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
为什么会返回false?对于第二个对象,与今天(06-05)相比,它在未来06-13时返回true
答案 0 :(得分:1)
因为新的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

答案 1 :(得分:0)
如果您尝试记录前两个值,则会看到不同的输出
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个日期与 getHours 和 getMonth 等其他道具进行比较,例如,您可以使用许多其他道具
详细了解日期对象 Date Javascript MDN
答案 2 :(得分:0)
@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
请注意以下两行代码,因为上述解决方案基于此。
✓以下两个陈述彼此相同
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)