Java Calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY),它会向后、向前还是未知?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1319473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:12:12  来源:igfitidea点击:

Java Calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY), will it roll backwards, forwards or unknown?

javacalendar

提问by Will

Suppose the following code is executed on the 22nd of August 2009 (a Saturday)

假设以下代码在 2009 年 8 月 22 日(星期六)执行

   Calendar c = Calendar.getInstance();
   c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

c.get(Calendar.DAY_OF_MONTH)will return 23. I'm interested in the conditions is would return 14 (last Sunday, rather than the next Sunday).

c.get(Calendar.DAY_OF_MONTH)将返回 23。我感兴趣的条件是将返回 14(上周日,而不是下周日)。

Are there any rules associated with the direction Calendar will roll the DAY_OF_MONTH/YEARwhen DAY_OF_WEEKis set? If so what are they?

是否有与方向相关的日历将推出的任何规则DAY_OF_MONTH/YEARDAY_OF_WEEK设置?如果有,它们是什么?

采纳答案by VoteyDisciple

It should always keep the same WEEK_OF_MONTH(http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#WEEK_OF_MONTH). From the documentation:

它应该始终保持不变WEEK_OF_MONTHhttp://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#WEEK_OF_MONTH)。从文档:

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get() may be different. For example, a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.

在设置或获取 WEEK_OF_MONTH 或 WEEK_OF_YEAR 字段时,日历必须确定月份或年份的第一周作为参考点。一个月或一年的第一周定义为从 getFirstDayOfWeek() 开始并至少包含该月或一年的 getMinimalDaysInFirstWeek() 天数的最早 7 天。周数 ..., -1, 0 在第一周之前;周数为 2、3、... 跟着它。请注意,get() 返回的规范化编号可能不同。例如,特定的 Calendar 子类可以将一年的第 1 周之前的一周指定为前一年的第 n 周。

回答by Jherico

From the Javadoc:

Javadoc

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

I interpret this to mean that given that you're setting day of week, it will end up being combined with week of month or week of year in order to produce the actual date and time.

我将此解释为,如果您设置的是星期几,它将最终与月份中的一周或一年中的一周相结合,以生成实际的日期和时间。

回答by Alexander Smirnov

the following formula returns "current" day in a week in range of [0;6]

以下公式在 [0;6] 范围内返回一周中的“当前”日

(d + numberOfDaysInAWeek - firstDayOfWeek) % numberOfDaysInAWeek

or add 1 if you would like range [1;7]

或者如果您想要范围 [1;7],则加 1

(d + numberOfDaysInAWeek - firstDayOfWeek) % numberOfDaysInAWeek + 1

dis what Calendar.get(Calendar.DAY_OF_WEEK)returns

d是什么Calendar.get(Calendar.DAY_OF_WEEK)返回

to get first day of a week, subtract formula's result from current date. The following code does it:

要获得一周的第一天,请从当前日期中减去公式的结果。下面的代码做到了:

final int currentDayOfWeek = (calendar.get(Calendar.DAY_OF_WEEK) + 7 - cal.getFirstDayOfWeek()) % 7;
cal.add(Calendar.DAY_OF_YEAR, -currentDayOfWeek);

回答by Hrvoje

You should also check what is the first day in a week. I also thought it is always Sunday, but this depend on local settings, and in my case Monday is the first day in week. Setting Sunday as first day of the week fixed my problem.

您还应该检查一周中的第一天是什么日子。我还以为总是星期天,但这取决于当地的设置,在我的情况下,星期一是一周中的第一天。将星期日设置为一周的第一天解决了我的问题。

回答by Michael Piefel

It depends, actually. Consider the following Java code. It is actually quite simple and I expect it to print the monday preceding 2011-09-18, that is 2011-09-12:

这取决于,实际上。考虑以下 Java 代码。它实际上很简单,我希望它打印 2011-09-18 之前的星期一,即 2011-09-12:

Calendar calendar = Calendar.getInstance(Locale.GERMANY);
System.out.printf("First day of week: %d%n%n", calendar.getFirstDayOfWeek());

calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n%n", calendar);

calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF (week %d)%n",
        calendar, calendar.get(Calendar.WEEK_OF_YEAR));
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF (week %d)%n", calendar,
        calendar.get(Calendar.WEEK_OF_YEAR));

But in fact the result is a bit different:

但实际上结果有点不同:

First day of week: 2

Starting day: 2011-09-18
Last monday: 2011-09-19

Starting day: 2011-09-18 (week 37)
Last monday: 2011-09-12 (week 37)

In other words, the result depends on whether my calendar knows that I might be interested in the week. The result actually changes if I query WEEK_OF_YEAR!

换句话说,结果取决于我的日历是否知道我可能对本周感兴趣。如果我查询,结果实际上会改变WEEK_OF_YEAR

回答by Anton

Depends on the first day of the week:

取决于一周的第一天:

 /**
 * Gets what the first day of the week is; e.g., <code>SUNDAY</code> in the U.S.,
 * <code>MONDAY</code> in France.
 *
 * @return the first day of the week.
 * @see #setFirstDayOfWeek(int)
 * @see #getMinimalDaysInFirstWeek()
 */
public int getFirstDayOfWeek()
{
    return firstDayOfWeek;
}

回答by yakup_y

You can use like this method.

您可以像这样使用这种方法。

public Integer whichDayOfWeek(Calendar calendar) {
            if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                return 1;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
                return 2;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
                return 3;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
                return 4;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
                return 5;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
                return 6;
            } else if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                return 7;
            } else {
                return null;
            }
        }

回答by Basil Bourque

Using java.time

使用 java.time

The modern approach is with the java.time classes that supplant the troublesome old legacy date-time classes.

现代方法是使用 java.time 类取代麻烦的旧的遗留日期时间类。

The java.time classes are much easier to work with. In particular, they remove the ambiguity raised in the Question. You can explicitly ask either for the earlierSunday or for the laterSunday.

java.time 类更容易使用。特别是,它们消除了问题中提出的歧义。您可以明确要求较早的周日或较晚的周日。

The LocalDateclass represents a date-only value without time-of-day and without time zone.

LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

The Monthenum provides a dozen pre-defined objects, one for each month of the year. These enum objects are safer to use, but you can instead use a plain number for the month. Unlike the legacy classes, these months have sane numbering, 1-12 for January-December.

Month枚举提供了十几个预定义的对象,一个是一年中每个月。这些枚举对象使用起来更安全,但您可以改为使用普通数字表示月份。与传统课程不同,这些月份的编号合理,1-12 月为 1-12。

LocalDate localDate = LocalDate.of( 2009 , Month.AUGUST, 22 );

The TemporalAdjusterinterface provides for manipulation of date-time values. The TemporalAdjustersclass (note the plural s) provides several handy implementations.

TemporalAdjuster接口提供对日期时间值的操作。在TemporalAdjusters类(注意是复数s)提供了一些方便的实现。

The previous& nextadjusters exclude the date itself from consideration. The previousOrSame& nextOrSamemethods return the date in question if it is indeed the desired day-of-week.

previousnext调节排除在考虑日期本身。在previousOrSamenextOrSame有关方法返回的日期,如果它确实是需要的某一天的一周。

The DayOfWeekenum provides seven pre-defined objects, one for each day of the week.

DayOfWeek枚举提供七个预定义的对象,一个星期中的每一天。

LocalDate previousSunday = localDate.with( TemporalAdjusters.previous ( DayOfWeek.SUNDAY ));
LocalDate previousOrSameSunday = localDate.with( TemporalAdjusters.previousOrSame ( DayOfWeek.SUNDAY ));

LocalDate nextSunday = localDate.with( TemporalAdjusters.next ( DayOfWeek.SUNDAY ));
LocalDate nextOrSameSunday = localDate.with( TemporalAdjusters.nextOrSame ( DayOfWeek.SUNDAY ));

Dump to console.

转储到控制台。

System.out.println ("localDate: " + localDate + " ( " + localDate.getDayOfWeek ().getDisplayName ( TextStyle.FULL, Locale.US )  + " )");
System.out.println ("previousSunday: " + previousSunday );
System.out.println ("nextSunday: " + nextSunday );

localDate: 2009-08-22 ( Saturday )

previousSunday: 2009-08-16

nextSunday: 2009-08-23

本地日期:2009-08-22(星期六)

上一个星期日:2009-08-16

下周日:2009-08-23



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多