Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Calendar Problem

25 views
Skip to first unread message

Me

unread,
Sep 1, 2004, 1:05:18 PM9/1/04
to
How do I get the actual Calendar time out of a Calendar object?

I am trying to save UTC time to a table column. However the Calendar
object always returns the current time, not the UTC time from its
utility methods. The get() method does return the actual Calendar time.

----------------
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
String actual = "";
actual += cal.get(Calendar.YEAR );
actual += "-";
actual += (cal.get(Calendar.MONTH ) + 1);
actual += "-";
actual += cal.get(Calendar.DAY_OF_MONTH );
actual += " ";
actual += cal.get(Calendar.HOUR_OF_DAY );
actual += ":";
actual += cal.get(Calendar.MINUTE );
actual += ":";
actual += cal.get(Calendar.SECOND );
actual += ".";
actual += cal.get(Calendar.MILLISECOND );
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
System.out.println( actual ); // this is right
System.out.println( ts.toString() ); // this is wrong
------------------

The above will alwys print the UTC time, then the current time, yet they
should be the same.

Steve Bosman

unread,
Sep 9, 2004, 5:04:55 PM9/9/04
to
Me <m...@a.com> wrote in message news:<ijnZc.43365$A8.21659@edtnps89>...

No, they shouldn't be the same. How does the Timestamp object know you
want a string formatted in UTC? In fact internally Timestamp uses
TimeZone.getDefault() to determine the timezone it will print for. You
should _never_ rely on toString() to give you anything useful. Try the
following:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println( df.format(ts));

HTH
Steve

0 new messages