日期时间和日期比较

时间:2012-05-01 18:09:16

标签: salesforce

为什么这句话会回归真实?我知道我正在将DateDateTime变量进行比较,但我正在寻找更具技术性的解释。

DateTime dt = DateTime.newInstance(2012,04,30,0,0,0);
system.debug(dt > Date.valueOf('2012-04-30'));

另外,2012-04-30之前的DateTime值(对于dt变量)是否也会返回true?

1 个答案:

答案 0 :(得分:1)

Superfell 在评论中指出,这可能是由于时区转换以及午夜(00:00:00)被追加到日期进行比较。简短的故事:他是正确的,因为午夜被附加到日期进行比较。详情如下。

我需要看到这一点,以便完全理解它;所以,我写了一段代码。

for(Integer mo=4; mo<6; mo++) // test April (4) and May (5) only
    for(Integer d=(mo==4?29:0); d<=(mo==5?2:30); d++) // test between 2012-04-29 and 2012-05-30
        for(Integer h=0; h<12; h++)
            for(Integer m=0; m<60; m++)
            {
                // this simulates a CreatedDate field (note it is generated using the newInstanceGMT method and not simply newInstance)
                // DateTime fields in Salesforce are stored in GMT then converted to the current User's time-zone. 
                DateTime dt1 = DateTime.newInstanceGMT(2012,mo,d,h,m,0); 
                Date dt2 = Date.valueOf('2012-04-30');
                if(dt1 > dt2) { 
                    system.debug(LoggingLevel.INFO,'DateTime:'+dt1+' > Date:'+dt2); }
            }

显示生成的调试日志:

USER_DEBUG|[9]|INFO|DateTime:2012-04-30 00:01:00 > Date:2012-04-30 00:00:00
USER_DEBUG|[9]|INFO|DateTime:2012-04-30 00:02:00 > Date:2012-04-30 00:00:00
USER_DEBUG|[9]|INFO|DateTime:2012-04-30 00:03:00 > Date:2012-04-30 00:00:00
...
USER_DEBUG|[9]|INFO|DateTime:2012-05-02 11:57:00 > Date:2012-04-30 00:00:00
USER_DEBUG|[9]|INFO|DateTime:2012-05-02 11:58:00 > Date:2012-04-30 00:00:00
USER_DEBUG|[9]|INFO|DateTime:2012-05-02 11:59:00 > Date:2012-04-30 00:00:00

简化解决方案将与Date.valueOf('2012-05-01');进行比较。但是,可以使用DateTime类型上的newInstanceGMT方法与CreatedDate字段进行比较。使用DateTime方法,需要考虑午夜。

DateTime dt1 = DateTime.newInstanceGMT(2012,mo,d,h,m,0); // simulated CreatedDate field
Date dt2 = Date.valueOf('2012-05-01'); 
if(dt1 > dt2) { 
    system.debug(LoggingLevel.INFO,'DateTime:'+dt1+' > Date:'+dt2); }

OR

DateTime dt1 = DateTime.newInstanceGMT(2012,mo,d,h,m,0); // simulated CreatedDate field
DateTime dt2 = DateTime.newInstanceGMT(2012,04,30,12,59,59); 
if(dt1 > dt2) { 
    system.debug(LoggingLevel.INFO,'DateTime:'+dt1+' > Date:'+dt2); }

这两种方法都产生了预期的结果:

USER_DEBUG|[9]|INFO|DateTime:2012-05-01 00:00:00 > Date:2012-04-30 12:59:59
USER_DEBUG|[9]|INFO|DateTime:2012-05-01 00:01:00 > Date:2012-04-30 12:59:59
USER_DEBUG|[9]|INFO|DateTime:2012-05-01 00:02:00 > Date:2012-04-30 12:59:59
...
USER_DEBUG|[9]|INFO|DateTime:2012-05-02 11:57:00 > Date:2012-04-30 12:59:59
USER_DEBUG|[9]|INFO|DateTime:2012-05-02 11:58:00 > Date:2012-04-30 12:59:59
USER_DEBUG|[9]|INFO|DateTime:2012-05-02 11:59:00 > Date:2012-04-30 12:59:59