Java:如何在Timestamp中添加秒数?

我无法在Java Timestamp中添加秒数。

我有这个,但它给了我相同的日期:

int sec = 600; java.sql.Timestamp ts_from_ws = new java.sql.Timestamp(retry_date); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(ts_from_ws.getTime()); cal.add(Calendar.SECOND,sec); java.sql.Timestamp ts_new_date_ws = new java.sql.Timestamp(cal.getTime().getTime()); 

你得到的代码对我有用。 作为一个简短但完整的计划:

 import java.util.*; import java.sql.*; public class Test { public static void main(String[] args) { long retryDate = System.currentTimeMillis(); int sec = 600; Timestamp original = new Timestamp(retryDate); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(original.getTime()); cal.add(Calendar.SECOND, sec); Timestamp later = new Timestamp(cal.getTime().getTime()); System.out.println(original); System.out.println(later); } } 

输出:

 2011-11-07 10:27:45.302 2011-11-07 10:37:45.302 

注意10分钟的差异,即600秒。

当然你会以这种方式失去亚毫秒的精度,这可能并不理想 – 而且它与我通常首先使用的时间戳相反 – 但它确实增加了秒……

另一种选择是直接使用Timestamp

 Timestamp original = ...; Timestamp later = new Timestamp(original.getTime() + (sec * 1000L)); later.setNanos(original.getNanos()); 

我总是喜欢简洁:

 int sec = 600; Timestamp later = new Timestamp(retry_date.getTime() + sec * 1000); 

或者如果你想要相对于“现在”:

 Timestamp later = new Timestamp(System.currentTimeMillis() + sec * 1000); 
 public void addTimeBySecondsDemo(Date date,int sec){ //int sec = 300; System.out.println("Given date:"+date); Calendar calender = Calendar.getInstance(); calender.setTimeInMillis(date.getTime()); calender.add(Calendar.SECOND, sec); Date changeDate=calender.getTime(); System.out.println("changeDate ..:"+changeDate); } 
 Timestamp.from(dto.getTimeModified().toInstant().plusSeconds(600)) 

java 8中 ,您可以利用新的java.time.Instant 。 在java.sql.TimeStamp ,从Java 1.8添加了两个新方法: public static Timestamp from(Instant instant)public Instant toInstant()

所以要添加秒,我们可以将TimeStamp转换为Instant,然后调用plusSeconds ,然后再调用TimeStamp:

 Timestamp ts_from_ws = new Timestamp(retry_date); Instant next600Sec = ts_from_ws.toInstant().plusSeconds(600); Timestamp ts_new_date_ws = TimeStamp.from(next600Sec); 

或者一行:

 Timestamp ts_new_date_ws = TimeStamp.from(new Timestamp(retry_date).toInstant().plusSeconds(600))