我的javascript代码如下:
let requestDate = sendDate + ' ' + sendTime + ':00'
requestDate = moment(requestDate, "DD-MM-YYYY HH:mm")
let currentDate = moment().add(3, 'h').format("DD-MM-YYYY HH:mm")
console.log(requestDate)
console.log(currentDate)
console.log('test')
if( requestDate <= currentDate){
console.log('1')
}
else {
console.log('2');
}
在控制台上看起来像这样:
为什么console.log的结果显示为2?
从我的代码中,它应该是console.log显示1
的结果答案 0 :(得分:2)
您正在将一个时刻对象(即:requestDate)与一个字符串(即:currentDate)进行比较。
您可以在以下代码段中看到这一点:
let requestDate = '07-09-2017' + ' ' + '12' + ':00'
requestDate = moment(requestDate, "DD-MM-YYYY HH:mm")
let currentDate = moment().add(3, 'h').format("DD-MM-YYYY HH:mm")
console.log('requestDate is: ' + typeof(requestDate) + ' its AND the value is: ' + requestDate.format("DD-MM-YYYY HH:mm"))
console.log('currentDate is: ' + typeof(currentDate) + ' its AND the value is: ' + currentDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
您有两种选择。
第一个选项
比较字符串日期。在这种情况下,您可以使用Query functions。在您的情况下,您可以使用:isSameOrAfter。
因此,您可以更改此行:
if( requestDate <= currentDate){
为:
if( moment(currentDate, "DD-MM-YYYY HH:mm").isSameOrAfter(moment(requestDate, "DD-MM-YYYY HH:mm"))) {
let requestDate = moment();
requestDate = moment(requestDate, "DD-MM-YYYY HH:mm").format("DD-MM-YYYY HH:mm");
let currentDate = moment().add(3, 'h').format("DD-MM-YYYY HH:mm")
console.log(requestDate)
console.log(currentDate)
console.log('test')
if( moment(currentDate, "DD-MM-YYYY HH:mm").isSameOrAfter(moment(requestDate, "DD-MM-YYYY HH:mm"))) {
console.log('1')
}
else {
console.log('2');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
第二个选项是比较时刻对象并仅在需要打印值时使用 .format(“DD-MM-YYYY HH:mm”)。
let requestDate = moment();
requestDate = moment(requestDate, "DD-MM-YYYY HH:mm")
let currentDate = moment().add(3, 'h');
console.log(requestDate.format("DD-MM-YYYY HH:mm"))
console.log(currentDate.format("DD-MM-YYYY HH:mm"))
console.log('test')
if( requestDate <= currentDate){
console.log('1')
}
else {
console.log('2');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
答案 1 :(得分:2)
您可以将当前日期更改为与请求日期相同的格式。目前,请求日期是时刻对象,当前日期是日期。
您可以使用下面的代码段。
let sendDate = "07-09-2017";
let sendTime = "17:05";
let requestDate = sendDate + ' ' + sendTime + ':00'
requestDate = moment(requestDate, "DD-MM-YYYY HH:mm")
let currentDate = moment(moment().add(3, 'h'), "DD-MM-YYYY HH:mm")
console.log(requestDate.toDate())
console.log(currentDate.toDate())
console.log('test')
if( requestDate.toDate() <= currentDate.toDate()){
console.log('1')
}
else {
console.log('2');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>