简体   繁体   English

日期比较无法正常工作

[英]Date comparison not working as expected

Hi I have the following if then statement in my JS code. 嗨,我在JS代码中有以下if语句。

    if (attributes.DATE > '10/20/2013'){
        html += '<b>Maximum percentage:</b> ' + aPerc + '%';
    }
    else {
        html += '<b>Percentage:</b> ' + aPerc + '%';    
    }

It seems to be working fine for October 2013 dates, and all January dates (no matter the year). 对于2013年10月的日期和所有1月的日期(无论年份如何),它似乎都可以正常工作。

For past October years, it will display "Maximum percentage:" for Oct. 1-19 and "Percentage" for Oct. 20-31st. 在过去的10月中,它将在10月1日至19日显示“最大百分比:”,在10月20日至31日显示“百分比”。

It does not work correctly for other months. 其他月份无法正常工作。 Eg Feb, March, April, etc. it displays "Maximum Percentage". 例如2月,3月,4月等,它显示“最大百分比”。

I am guessing it has something to do with my date format? 我猜想这与我的日期格式有关吗? Thank you. 谢谢。

I would do this: 我会这样做:

var date1 = new Date(attributes.DATE);
var date2 = new Date('10/20/2013');

if (date1 > date2){
    html += '<b>Maximum percentage:</b> ' + aPerc + '%';
}
else {
    html += '<b>Percentage:</b> ' + aPerc + '%';    
}

That way, you're comparing two date objects rather than two string objects. 这样,您将比较两个日期对象而不是两个字符串对象。

You're doing a string comparison, but the order of the fields in the string will not give you a date-order comparison. 您正在进行字符串比较,但是字符串中字段的顺序不会为您提供日期顺序的比较。 (You'd get one if both strings were in yyyy/MM/dd order...) (如果两个字符串均为yyyy/MM/dd顺序,您将得到一个...)

If DATE is a Date instance, you can do this: 如果DATEDate实例,则可以执行以下操作:

if (attributes.DATE >= new Date(2013, 9, 21)){

...which will be true from midnight on October 21st (the month value starts with 0 = January, so 9 = October). ...从10月21日午夜开始就是正确的(月份值从0 =一月开始,所以9 =十月)。 Note I made it >= and the 21st rather than the 20th, because I assumed if you're looking for something > '10/20/2013' , you mean the 21st or later (as opposed to meaning "any time after midnight on the 20th"). 请注意,我将其设置为>=和21号,而不是20号,因为我假设如果您要查找> '10/20/2013' ,则表示21号或更高版本(而不是意思是“ 20号”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM