我想将给定的日历实例的时间戳设置为一周的开头(星期一),而是返回一个看似完全不相关的时间戳 – 除非我在这之前访问任何日历的字段.我在下面提供了一个示例,请在Ideone中看到这个可运行的示例.
这是预期的行为吗?这背后的逻辑是什么?是的,我听说过Joda Time.
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()));
}
}
解决方法:
文档中的Field Manipulation章节清楚地解释了它.它虽然有点怪异.
Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling
set(Calendar.MONTH, Calendar.SEPTEMBER) sets the date to September 31, 1999.
This is a temporary internal representation that resolves to October 1, 1999 if
getTime()is then called. However, a call to set(Calendar.DAY_OF_MONTH, 30) before the
call to getTime() sets the date to September 30, 1999, since no recomputation occurs
after set() itself.
编辑
从日历字段解决方案部分相同的文档
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
标签:java,calendar
来源: https://codeday.me/bug/20190529/1175671.html