以下のコードは、週計算の問題のあるjoda-time実装を示しています。この動作はバグではありませんが、Joda-Timeが月曜日から日曜日の週にISO標準を使用する設計上の決定です。(おそらくそれはバグであるはずですか?)
週番号を計算する必要がある日付を考えると、この計算は本質的にi18nでなければなりません。意味ユーザーの地域設定に基づいて、正しい週番号を考慮する必要があります。
以下のデモコードは、Joda-Timeによる誤った計算と、JDKによる正しい計算を示しています。アプリケーションでは、日付操作の優れたソリューションであるJoda-Timeに固執しようとしています。では、2つの時間計算ライブラリを混在させる必要がありますか?私は明らかにしたくないのですが、これは安全なことでさえありますか、それとも私はコーナーケースに陥ります(日付、カレンダーの経験があるので、これはJavaにとって苦痛な問題であるという事実を知っています)。
結論:説明されている要件に対して推奨されるベストプラクティスは何ですか?
問題のデモンストレーションコード
正しい週の計算例については、週番号が表示されているこのオンラインカレンダーを参照してください。
public class JodaTest {
static DateTimeFormatter formatter = DateTimeFormat.forPattern("ww yyyy");
static SimpleDateFormat jdkFormatter = new SimpleDateFormat("ww yyyy");
public static void main(String[] args) {
DateTime time = new DateTime(/*year*/2009, /*monthOfYear*/12, /*dayOfMonth*/6, /*hourOfDay*/23, /*minuteOfHour*/0, /*secondOfMinute*/0, /*millisOfSecond*/0);
StringBuilder buffer = new StringBuilder()
.append("Testing date ").append(time.toString()).append("\n")
.append("Joda-Time timezone is ").append(DateTimeZone.getDefault()).append(" yet joda wrongly thinks week is ").append(formatter.print(time)).append("\n")
.append("JDK timezone is ").append(TimeZone.getDefault().getID()).append(" yet jdk rightfully thinks week is ").append(jdkFormatter.format(time.toDate())).append(" (jdk got it right ?!?!)");
System.out.println(buffer.toString());
}
}
出力:
Testing date 2009-12-06T23:00:00.000+02:00
Joda-Time timezone is Asia/Jerusalem yet joda wrongly thinks week is 49 2009
JDK time zone is Asia/Jerusalem yet jdk rightfully thinks week is 50 2009 (jdk got it right ?!?!)