2

このステートメントが true を返すのはなぜですか? Datea を変数と比較していることは理解していDateTimeますが、より技術的な説明を探しています。

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

また、2012 年 4 月 30 日より前の (dt 変数の) DateTime 値も true を返しますか?

4

1 に答える 1

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');です。newInstanceGMTただし、 DateTime 型のメソッドを使用して CreatedDate フィールドと比較することは可能です。DateTime メソッドを使用する場合、午前 0 時を考慮する必要があります。

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); }

また

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
于 2012-05-01T19:40:19.157 に答える