我无法为Java时间戳添加秒数。
我有这个,但是,它给了我相同的日期:
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
Timestamp original = ...; Timestamp later = new Timestamp(original.getTime() + (sec * 1000L)); later.setNanos(original.getNanos());