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