使用设置日历中的日期字段
myCalender.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
是否将这一天设置为下周五或上周五或可能是最接近的?
另外,如果我没有为日历设置年份或任何其他字段,默认值是多少?
最佳答案
都不是。然而。情况很复杂。但不要使用日历
,见下文。
来自the documentation of the two-arg set
method :
Sets the given calendar field to the given value. The value is not interpreted by this method…
因此,在这次调用期间,它只是将星期几字段设置为星期五。年、月、日保持不变,即日期未有效更改。然而。
如果Calendar
最终计算并解析其字段,
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.
如果您只设置了星期几(这可能会与其他字段发生冲突),则适用以下组合:
YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK
所以它会选择同一周的星期五。
一周的定义由日历
的第一天字段决定。它的初始值由Calendar
的区域设置决定,您可以通过getFirstDayOfWeek()
和setFirstDayOfWeek()
来控制它。这反过来意味着,欧洲语言环境中之前设置为星期日的日历
的默认行为将返回到上一个星期五,而美国语言环境中的日历
将返回到上一个星期五。选择下周五。
如果您在设置星期几之后但在计算字段之前还设置了其他字段,则情况不同。
默认值?
通常,Calendar
字段的默认值是 JVM 时区中的当前日期和时间(通常但并非总是与您设备的时区相同)。
你不需要关心
好消息是您不需要关心。无论如何,Calendar
类早已过时,而且(回想起来)它的设计也很糟糕,所以您不应该使用它。请改用现代 Java 日期和时间 API java.time
。和它一起工作真是太好了。根据您的需要,您可以使用 LocalDate
表示日期,或使用 ZonedDateTime
表示带有时区的日期和时间。
现代类(class)为您提供了更好的清晰度和更大的灵 active 。例如:
LocalDate ld = LocalDate.now(ZoneId.of("Pacific/Saipan"));
// the following calls do what the method names say
ld = ld.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
ld = ld.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));
ld = ld.with(TemporalAdjusters.previous(DayOfWeek.FRIDAY));
ld = ld.with(TemporalAdjusters.previousOrSame(DayOfWeek.FRIDAY));
// set to Friday in the same ISO week
ld = ld.with(ChronoField.DAY_OF_WEEK, DayOfWeek.FRIDAY.getValue());
// set to Friday in the same US week
ld = ld.with(WeekFields.SUNDAY_START.dayOfWeek(),
DayOfWeek.FRIDAY.get(WeekFields.SUNDAY_START.dayOfWeek()));
问题:我可以在 Android 上使用 java.time
吗?
是的,java.time
在 Android 设备上运行良好。它只需要至少 Java 6。
- 在 Java 8 及更高版本以及新的 Android 设备(据我所知,从 API 级别 26 开始)中,新的 API 是内置的。
- 在 Java 6 和 7 中获取 ThreeTen Backport,即新类的向后移植(ThreeTen for JSR 310,其中首次描述了现代 API)。
- 在(较旧的)Android 上,使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。确保从包
org. Threeten.bp
和子包中导入日期和时间类。
链接
- Oracle tutorial: Date Time ,解释如何使用
java.time
。 - ThreeTen Backport project
- ThreeTenABP , Android 版 ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project ,有非常详尽的解释。
- Java Specification Request (JSR) 310 .
关于java - 在 Android 中设置日历字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48915053/