なぜ3月30日および2020年3月1日の間の差は、誤って28日間の代わりに29を与えるのでしょうか?

ジョー:
TimeUnit.DAYS.convert(
   Math.abs(
      new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse("30-03-2020 00:00:00").getTime() - 
      new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").parse("1-03-2020 00:00:00").getTime()
   ),
   TimeUnit.MILLISECONDS)

タイムゾーン/場所が問題になる可能性がある結果が28であり、それは29でなければなりませんか?

アンドレアス:

問題は(2020年3月8日(日曜日 ) に)夏時間シフトのがあるので、ということである28日と23時間これらの日付の間。TimeUnit.DAYS.convert(...) 切り捨て、28日に結果を。

問題を表示するには(私は米国東部のタイムゾーンにいます):

SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
long diff = fmt.parse("30-03-2020 00:00:00").getTime() -
            fmt.parse("1-03-2020 00:00:00").getTime();

System.out.println(diff);
System.out.println("Days: " + TimeUnit.DAYS.convert(Math.abs(diff), TimeUnit.MILLISECONDS));
System.out.println("Hours: " + TimeUnit.HOURS.convert(Math.abs(diff), TimeUnit.MILLISECONDS));
System.out.println("Days: " + TimeUnit.HOURS.convert(Math.abs(diff), TimeUnit.MILLISECONDS) / 24.0);

出力

2502000000
Days: 28
Hours: 695
Days: 28.958333333333332

修正するには、例えば、DSTを持っていない時間帯を使用してUTC

SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
long diff = fmt.parse("30-03-2020 00:00:00").getTime() -
            fmt.parse("1-03-2020 00:00:00").getTime();

出力

2505600000
Days: 29
Hours: 696
Days: 29.0

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=6233&siteId=1