日期引用
hutool DateTime 使用
offset、offsetNew 区别
offset 会改变自身的时间,并且返回偏移后的时间,返回的对象是自身,当使用一个新对象接收这个offset返回的方法时,再对新对象进行修改,则原本的对象值也会修改,他们是同一个对象
offsetNew 会先clone一个时间对象,并返回这个新的对象,所以是不会改变自身的时间
DateTime.class offset 方法
public DateTime offset(DateField datePart, int offset) {
if (DateField.ERA == datePart) {
throw new IllegalArgumentException("ERA is not support offset!");
}
final Calendar cal = toCalendar();
//noinspection MagicConstant
cal.add(datePart.getValue(), offset);
DateTime dt = mutable ? this : ObjectUtil.clone(this);
return dt.setTimeInternal(cal.getTimeInMillis());
}
DateTime.class offsetNew 方法
public DateTime offsetNew(DateField datePart, int offset) {
final Calendar cal = toCalendar();
//noinspection MagicConstant
cal.add(datePart.getValue(), offset);
DateTime dt = ObjectUtil.clone(this);
return dt.setTimeInternal(cal.getTimeInMillis());
}
从源码上看,offset方法会改变自身的时间,所以在使用过程中要注意
代码示例:`
java
文档更新时间: 2024-03-25 11:24 作者:朱灿奕