Reputation: 1727
I am trying to get the timestamp.
This works.
final Calendar cal = new GregorianCalendar(tz);
final Timestamp ts = new Timestamp(cal.getTimeInMillis());
But, I don't want to reinstantiate the variables each and every time, I need to get the timestamp. How can I do that?
I tried to do..
//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());
This doesn't seem to work. Could you suggest?
Upvotes: 1
Views: 2723
Reputation: 340863
Maybe I am missing something, but this:
final Calendar cal = new GregorianCalendar(tz);
final Timestamp ts = new Timestamp(cal.getTimeInMillis());
is equivalent to much more lightweight:
final Timestamp ts = new Timestamp(System.currentTimeMillis());
That's because new GregorianCalendar
with specific time zone points to now. And since calling getTimeInMillis()
"ignores" time zone, you essentially ask for current time in millis since epoch. Which can be done with System.currentTimeMillis()
.
Timestamp
class is:
A thin wrapper around
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.
Upvotes: 3