一尘不染

Java:如何为时间戳添加秒?

java

我无法为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());

阅读 884

收藏
2020-12-03

共1个答案

一尘不染

您拥有的代码适合我。作为简短但完整的程序:

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());
2020-12-03