下面的代码演示了周计算的有问题的 joda-time 实现。此行为不是错误,而是设计决定 Joda-Time uses the ISO standard Monday to Sunday week. (也许它应该是一个错误?)
给定一个日期,我需要计算周数,这个计算本质上必须是 i18n。这意味着我必须根据用户的区域设置考虑正确的周编号。
下面的演示代码显示了 Joda-Time 的错误计算和 JDK 的正确计算,在应用程序中,我们尝试坚持使用 Joda-Time 作为日期操作的卓越解决方案。那么,我应该混合使用两个时间计算库吗?我显然不想这样做,这是否是一件安全的事情,或者我会遇到极端情况(我有使用 Date、Calendar 的经验,我知道这对 Java 来说是一个痛苦的问题)。
底线:针对所述要求推荐的最佳实践是什么?
问题演示代码
请看这个online calendar displaying week numbers正确的周计算示例。
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 ?!?!)
最佳答案
最好的解决方案是编写一个 DateTimeField
的实现,它封装了根据区域设置提取所需值的逻辑。在内部,您可能仍会依赖 JDK 数据。目的是将所有 JDK 代码包装在一个可重用的类中。然后你可以像这样使用它:
int value = dateTime.get(new LocaleAwareWeekField("en_GB"));
关于java - Joda时间周计算推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214798/