user1539343
user1539343

Reputation: 1669

Timezone conversion using jodatime

I found in one of the posts in this forum:

SimpleDateFormat dateformat = new SimpleDateFormat(format);
dateformat.setTimeZone(TimeZone.getDefault());
dateformat.format(date);

I am not sure whether it really will work. The input parameter doesn't mention what timezone it is in. In that case how will it know how to convert?

Upvotes: 2

Views: 45

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86744

A java.util.Date (the base class of java.sql.Date) always represents instants in time in UTC. The timezone is an adjustment that you apply when you are formatting the time for display, as you are doing.

So the answer is it doesn't need to know the "input timezone" because there isn't one -- instants in time are always represented internally in UTC.

It really pays to get into this mindset when dealing with time values. If you recognize that instants of time are really independent of the timezone they occur in, and always store them in UTC, you can eliminate a huge source of errors and wasted effort. Think "Instants are UTC; timezones only apply when interfacing with the outside world". When you are required to accept an input with a timezone, the first thing you should do is convert to UTC internally. Do all persistence and manipulation in UTC and then apply the timezone only on the way back out.

Upvotes: 3

Related Questions