Re: help with preparedStatement.setTimestamp with Calendar
Shankar Unni <[email protected]>
| Newsgroups | gmane.comp.db.mysql.java |
|---|---|
| Message-ID | <[email protected]> |
Dan Jatnieks wrote:
> Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
> Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
>
> Date startdate = Date.valueOf("2006-01-01");
> cal.setTime(startdate);
> utc.setTime(cal.getTime());
>
> String ins = "INSERT INTO t (datestamp) VALUES ( ?)";
> // Use the UTC Calendar to create a new timestamp and the target
> // Calendar to adjust it to the correct timezone and set the
> // timestamp value.
> Timestamp tstamp = new Timestamp(utc.getTimeInMillis());
> stmt.setTimestamp(2, tstamp, cal);
I'm pretty sure this is wrong - it will reconvert the date back to your
timezone. You need to specify "utc" as the last argument above, and you
don't need to do "utc.setTime()" either:
This is also dangerous:
Date startdate = Date.valueOf("..."); // Notice that this will also
This will parse the date in the current system timezone. Be sure to
parse the date in the appropriate timezone first. If you meant EST, you
need to do:
Calendar utcCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
TimeZone localtz = TimeZone.getTimeZone("EST"); // or whatever
// This is how you parse a date in a known timezone:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.setTimeZone(localtz);
Date startdate = fmt.parse("2006-02-01");
// Now you need to pass that to the DB:
PreparedStatement ps = ....;
ps.setTimestamp(1, new Timestamp(startdate.getTime()), utcCal);
Some of this stuff can be done in advance (like setting up the
SimpleDateFormat, though beware of sharing such a SimpleDateFormat
between threads - either synchronize it, or make it local or thread-local).
Ditto for the utcCal object - you need to make it thread-safe yourself
in the same way.
--
MySQL Java Mailing List
For list archives: http://lists.mysql.com/java
To unsubscribe: http://lists.mysql.com/[email protected]