1

我正在尝试获取时间戳。

这行得通。

final Calendar cal = new GregorianCalendar(tz);
final Timestamp ts = new Timestamp(cal.getTimeInMillis());

但是,我不想每次都重新实例化变量,我需要获取时间戳。我怎样才能做到这一点?

我试着做..

//instantiate the variables.

    private final Calendar cal = new GregorianCalendar(tz);
    private final Timestamp ts = new Timestamp(cal.getTimeInMillis());

Inside a method()

    // trying to ask calendar to recalculate the time -- not working.
    cal.setTimeZone(tz); // I tried cal.clear() but it is giving me time during 1970 which I don't want.
    ts.setTime(cal.getTimeInMillis());

这似乎不起作用。你能建议吗?

4

2 回答 2

3

也许我错过了一些东西,但是这个:

final Calendar cal = new GregorianCalendar(tz);
final Timestamp ts = new Timestamp(cal.getTimeInMillis());

相当于更轻量级:

final Timestamp ts = new Timestamp(System.currentTimeMillis());

那是因为GregorianCalendar带有特定时区的 new 指向now。并且由于调用getTimeInMillis()“忽略”时区,您基本上要求自纪元以来以毫秒为单位的当前时间。可以用System.currentTimeMillis().

Timestamp类是:

一个薄薄的包装纸java.util.Date

And Date represents point in time, irrespective to time zone. You cannot create neither Timestamp nor Date in arbitrary time zone. These classes do not hold such information. In other words calendar object representing 14:00 in GMT+1 and 13:00 GMT+0 will result in exactly the same Date and Timestamp objects - because these dates are the same.

于 2012-08-28T16:43:08.607 回答
2

Try System.currentTimeMillis() to avoid creating a calendar.

于 2012-08-28T16:43:11.590 回答