我想将给定日历实例的时间戳设置为一周的开始(星期一),相反,它返回一个看似完全不相关的时间戳 - 除非我在这样做之前访问日历的任何字段。我在下面提供了一个示例,另请参阅此可运行示例Ideone.
这是预期的行为吗?这背后的逻辑是什么?是的,我听说过乔达时间。
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
class MyTest {
private static Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"), Locale.FRANCE);
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
public static void main(String[] args) {
// Set to any date.
calendar.set(2013, 10, 3);
System.out.println(dateFormat.format(calendar.getTime()));
// Set to another day.
calendar.set(2014, 0, 15);
// --- THE WTF STARTS HERE ---
// Uncommenting the line below returns the correct date in the end.
// calendar.getTime();
// Set to monday of current week.
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
// Expected outdate is 20140113
System.out.println(dateFormat.format(calendar.getTime()));
}
}
文档中的“字段操作”章节对此进行了清楚的解释。但它的工作原理很奇怪。
http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html
示例:考虑最初设置为 1999 年 8 月 31 日的 GregorianCalendar。
set(Calendar.MONTH, Calendar.SEPTEMBER) 将日期设置为 1999 年 9 月 31 日。
这是临时内部表示,如果满足以下条件,则解决日期为 1999 年 10 月 1 日:
然后调用 getTime()。但是,在之前调用 set(Calendar.DAY_OF_MONTH, 30)
调用 getTime() 将日期设置为 1999 年 9 月 30 日,因为没有重新计算发生
在 set() 本身之后。
EDIT
来自同一文档的日历字段解析部分
If there is any conflict in calendar field values, Calendar gives priorities to
calendar fields that have been set more recently. The following are the default
combinations of the calendar fields. The most recent combination, as determined
by the most recently set single field, will be used.
For the date fields:
YEAR + MONTH + DAY_OF_MONTH
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK
YEAR + DAY_OF_YEAR
YEAR + DAY_OF_WEEK + WEEK_OF_YEAR
我认为MONTH和DAY_OF_WEEK之间的区别就是这样。如果您在最后一个语句中设置 MONTH,它将与 YEAR+MONTH+DAY_OF_MONTH 匹配并覆盖所有这些。如果您设置 DAY_OF_WEEK,它将与 YEAR+DAY_OF_WEEK+WEEK_OF_YEAR 匹配,因此不会覆盖月份值。或类似的东西。说实话,我越看越觉得破碎。这根本没有意义。最好继续使用 JodaTime
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)