2012-05-01 240 views
2

此聲明爲何會返回true?我知道我將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

我認爲它可能是TZ相關的,不認爲僅日期VAL有任何TZ信息。 – superfell

+0

不錯,但DateTime.TimeInstance(2012,04,30,12,0,0);''也返回true,並且12-noon超過補償時區差異。 –

+2

但這會始終大於日期。 (我想象的日期確實是比較的日期+午夜) – superfell

回答

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 

simplist解決將是比較反對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