我在 Java.sql.Timestamp 对象中有一个日期(变量->confirmedDeliveryDate),我想创建一个不同的对象并向其添加几天。我创建了 ts 作为不同的时间戳变量,并使用了以下逻辑。我能够成功添加天数。但是,一旦 ts 更新为新时间,confirmedDeliveryDate 也会更新为新日期。当我为 ts 创建一个新对象时,为什么要更新confirmedDeliveryDate。并请提出相同的解决方案。
Timestamp ts = new Timestamp(0L);
ts=confirmedDeliveryDate;
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
cal.add(Calendar.DAY_OF_WEEK, 5);
ts.setTime(cal.getTime().getTime());
ts = new Timestamp(cal.getTime().getTime());
最佳答案
通过编码
ts=confirmedDeliveryDate;
您丢弃新创建的时间戳并将其替换为对 confirmedDeliveryDate
的引用
现在 ts 和confirmedDeliveryDate 是同一个,并且通过对其中一个调用setTime,两个变量名称的值(引用相同的对象)将会改变.
尝试这样:
Calendar cal = Calendar.getInstance();
cal.setTime(confirmedDeliveryDate );
cal.add(Calendar.DAY_OF_WEEK, 5);
Timestamp ts = new Timestamp(cal.getTime().getTime());
关于java - 将 Timestamp 对象的值复制到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34529602/