java - 设置 DAY_OF_WEEK 返回意外结果

标签 java calendar

我想将给定日历实例的时间戳设置为一周的开始(星期一),但它返回一个看似完全不相关的时间戳 - 除非我在这样做之前访问日历的任何字段。我在下面包含了一个示例,另请参阅 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 章节解释得很清楚。不过,它只是工作起来很奇怪。

http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

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 匹配,因此不会覆盖月份值。或类似的东西。老实说,我越看越觉得它 splinter 。这根本没有意义。最好继续使用 JodaTime

关于java - 设置 DAY_OF_WEEK 返回意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20631866/

相关文章:

java - 访问自定义组件的 AttributeSet 中的属性

java - 此代码可用于连接到 SQL Server 2008 吗?

api - Google Calendar Api,有 session 室吗?

Javascript 生成的 .ics 文件可以在 Chrome 和 Firefox 中打开,但不能在 IE 中打开

Java 可能的有损转换 Double 到 Int

java - 查找android存储中的所有mp3文件

ruby-on-rails - 如何在 Rails 事件日历插件中显示事件时添加弹出面板?

java - 比较日期是否早于 24 小时

java - 计算当前时间与某一天之间的时间

java - 更改列表中的项目并排序然后列出