下面的代码演示了周计算的有问题的 joda-time 实现。这种行为不是错误,而是设计决策Joda-Time 使用 ISO 标准的周一至周日周。(也许它应该是一个错误?)
给定一个我需要计算周数的日期,这个计算本质上必须是 i18n。这意味着我必须根据用户的区域设置考虑正确的周编号。
下面的演示代码显示了 Joda-Time 的错误计算和 JDK 的正确计算,在应用程序中,我们尝试坚持 Joda-Time 作为日期操作的优越解决方案。那么,我应该混合两个时间计算库吗?我显然不希望这样做,这是否是安全的事情,或者我会遇到极端情况(有使用日期、日历的经验,我知道这对 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 ?!?!)