java - Set method for Java Calendar only works if I do a print of it
问题描述
I am facing a problem I really don't understand. I am trying to use the set method on a Calendar but it modifies the values only if I print it, here is the code:
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));
This previous code gives me the output:
Date set: Mon Mar 02 00:00:00 CET 2020 Day of month: 2
And if I uncomment the "necessary print", then I get:
Necessary print: Tue Mar 31 23:07:17 CEST 2020 Date set: Mon Mar 30 00:00:00 CEST 2020 Day of month: 30
I'm really wondering why a print can affect this method, thanks in advance for help!
解决方案
The documentation of the Calendar class states:
The calendar fields can be changed using three methods:
set()
,add()
, androll()
.set(f, value)
changes calendar fieldf
tovalue
. In addition, it sets an internal member variable to indicate that calendar fieldf
has been changed. Although calendar fieldf
is changed immediately, the calendar'stime
value in milliseconds is not recomputed until the next call toget()
,getTime()
,getTimeInMillis()
,add()
, orroll()
is made. Thus, multiple calls toset()
do not trigger multiple, unnecessary computations. As a result of changing a calendar field usingset()
, 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: You need to call cal.getTime()
to update the values.
推荐阅读
- excel - Excel:如何在刷新所有连接之前暂停计算?
- php - 基于级别创建动态数组索引
- reactjs - 无法更新状态变量的特定键
- sql - 序列号自动生成
- r - R readxl:如何指定选定列的列类型
- chocolatey - 如何更改已安装 Chocolatey 包的 installargs 值?
- security - 如果登录成功,Facebook 或 Google 登录是否可以为每个用户返回一些常量和秘密值?
- sql-server - SQL Server 数据迁移/复制
- python - defaultdict 比普通字典慢
- machine-learning - 如何修复训练 SSD 中的“检查失败:background_label_id != label (0 vs. 0) Found background label in the dataset”?