Reputation: 1827
I put my project in the hosting whose time zone is different from my place.
In my web project I use "Timestamp" to insert the time into my database. So I need to get the time of Chicago(my time zone).
I use Joda time to get the time of different time zone.
My codes as follows:
DateTime dt = new DateTime();
DateTime dtChicago =dt.withZone(DateTimeZone.forID("America/Chicago"));
java.sql.Timestamp timeStamp = new java.sql.Timestamp(dtChicago.getMillis());
However when I test it ,I found the follows print the same milliseconds
DateTime dtLondon = dt.withZone(DateTimeZone.forID("Europe/London"));
System.out.println(dtLondon.getMillis());
DateTime dtChicago = dt.withZone(DateTimeZone.forID("America/Chicago"));
System.out.println(dtChicago.getMillis());
So how can I get the exact "Chicago" time zone time and inject it into Timestamp?
Upvotes: 0
Views: 926
Reputation: 279880
I found the follows print the same milliseconds
Doesn't that make sense to you? The time where I am right now might differ from the time where you are, but the amount of time that has elapsed since Unix epoch is the same.
A timestamp is that amount of time. It does not have a concept of timezone. You can store it directly as you have it.
When you'll need to format it to show it to your users, you will provide a timezone and the conversion will take care of performing the time differential for the time zone.
Upvotes: 2
Reputation: 29673
You can get time of specified time zone with DateTimeZone::convertUTCToLocal method
long europeMillis = DateTimeZone.forID("Europe/London").convertUTCToLocal(dt.getMillis());
long americaMillis = DateTimeZone.forID("America/Chicago").convertUTCToLocal(dt.getMillis());
Upvotes: 0
Reputation: 6306
You cannot put a TimeZone into a Timestamp object. When interacting with a database, you need to provide a Calendar
for both setting into a PreparedStatement
and getting from a ResultSet
. The Calendar
needs to be set to the TimeZone you want the data stored in the database. Normalizing all data to UTC presents many advantages for dealing with data from multiple timezones. It also eliminates the "hour of ambiguity" caused by DST when an hour is repeated.
Upvotes: 0