gpt4 book ai didi

java - Java 日历的设置方法仅在我打印它时才有效

转载 作者:行者123 更新时间:2023-12-02 01:01:51 26 4
gpt4 key购买 nike

我遇到了一个我真的不明白的问题。我试图在日历上使用 set 方法,但只有在打印它时它才会修改值,代码如下:

Calendar cal = Calendar.getInstance();
cal.set(2020,2,31);
// System.out.println("Necessary print: " + cal.getTime());

cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
// reset time
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);

System.out.println("Date set: " + cal.getTime());
System.out.println("Day of month: " + cal.get(Calendar.DAY_OF_MONTH));

前面的代码给了我输出:

Date set: Mon Mar 02 00:00:00 CET 2020
Day of month: 2

如果我取消注释“必要的打印”,那么我会得到:

Necessary print: Tue Mar 31 23:07:17 CEST 2020
Date set: Mon Mar 30 00:00:00 CEST 2020
Day of month: 30

我真的很想知道为什么打印会影响这个方法,提前感谢您的帮助! 😅

最佳答案

documentation Calendar 类的状态:

The calendar fields can be changed using three methods: set(), add(), and roll(). set(f, value) changes calendar field f to value. In addition, it sets an internal member variable to indicate that calendar field f has been changed. Although calendar field f is changed immediately, the calendar's time value in milliseconds is not recomputed until the next call to get(), getTime(), getTimeInMillis(), add(), or roll() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations. As a result of changing a calendar field using set(), other calendar fields may also change, depending on the calendar field, the calendar field value, and the calendar system. In addition, get(f) will not necessarily return value set by the call to the set method after the calendar fields have been recomputed. The specifics are determined by the concrete calendar class.

TL;DR:您需要调用 cal.getTime() 来更新值。

关于java - Java 日历的设置方法仅在我打印它时才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60554751/

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