Java: How to add seconds to Timestamp?

2020-05-19 06:41发布

I fail to add seconds to Java Timestamp.

I have this, but, it gives me the same date:

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());

5条回答
神经病院院长
2楼-- · 2020-05-19 06:55
Timestamp.from(dto.getTimeModified().toInstant().plusSeconds(600))
查看更多
Luminary・发光体
3楼-- · 2020-05-19 07:06

I've always favoured brevity:

int sec = 600;

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

or if you want relative to "now":

Timestamp later = new Timestamp(System.currentTimeMillis() + sec * 1000);
查看更多
乱世女痞
4楼-- · 2020-05-19 07:09

In java 8, you can leverage the new java.time.Instant. In java.sql.TimeStamp, two new method are added from java 1.8: public static Timestamp from(Instant instant) and public Instant toInstant().

So to add sec, we can convert the TimeStamp to Instant and then call plusSeconds and then back to 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);

Or one line:

Timestamp ts_new_date_ws = TimeStamp.from(new Timestamp(retry_date).toInstant().plusSeconds(600))
查看更多
唯我独甜
5楼-- · 2020-05-19 07:10

The code you've got works for me. As a short but complete program:

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);
    }
}

Output:

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

Note the difference of 10 minutes, i.e. 600 seconds.

Of course you lose the sub-millisecond precision this way, which may well not be ideal - and it goes against what I'm normally use a timestamp for in the first place - but it does add the seconds...

Another option would be to just use Timestamp directly:

Timestamp original = ...;
Timestamp later = new Timestamp(original.getTime() + (sec * 1000L));
later.setNanos(original.getNanos());
查看更多
▲ chillily
6楼-- · 2020-05-19 07:17
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);                
}
查看更多
登录 后发表回答