Java:如何为时间戳添加秒数? [英] Java: How to add seconds to Timestamp?

查看:83
本文介绍了Java:如何为时间戳添加秒数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我未能为 Java 时间戳添加秒数.

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

推荐答案

你得到的代码对我有用.作为一个简短但完整的程序:

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

输出:

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

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

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...

另一种选择是直接使用 Timestamp:

Another option would be to just use Timestamp directly:

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

这篇关于Java:如何为时间戳添加秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆