gpt4 book ai didi

java - 设置 DAY_OF_WEEK 返回意外结果

转载 作者:搜寻专家 更新时间:2023-11-01 02:09:39 24 4
gpt4 key购买 nike

我想将给定日历实例的时间戳设置为一周的开始(星期一),但它返回一个看似完全不相关的时间戳 - 除非我在这样做之前访问日历的任何字段。我在下面包含了一个示例,另请参阅 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com