Rob L
Rob L

Reputation: 3304

How to print a date in a specific time zone?

I asked this question earlier, but am still not sure how to go about solving my problem. I am hoping to find the best way to set the time zone of a user and then extract the date in the users time zone (and not servers local time zone). Some code will clarify...(Note: this code is a simplification of my problem)

long t = 1436842840327L;
Calendar c = Calendar.getInstance();
c.setTimeInMillis(t);
c.setTimeZone(TimeZone.getTimeZone("US/Alaska"));
System.out.println(c.getTime());
System.out.println(c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.MILLISECOND));

outputs

Mon Jul 13 23:00:40 EDT 2015
19:0:327 //<--- why is hour not 23???

But I want it to output

Mon Jul 13 23:00:40 EDT 2015
23:0:327

I have a web service that is provided a Calendar object based on the web users local time. I then need to process this Calendar object on the server side so I have to look up the users time zone in the database, set it and then extract the hour use in querying a database. What ends up happening is both the Calendar.DAY_OF_MONTH and Calendar.HOUR do not match the date that the Calendar object represents. To summarize, I want the user to supply a Calendar object, set the time zone and then extract the correct hour and day.

Upvotes: 0

Views: 297

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85809

Because you MUST NOT use Calendar#toString nor Date#toString to get a string representation of a date. Instead, use SimpleDateFormat.

Date yourDate = ...
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("US/Alaska"));
System.out.println(sdf.format(yourDate));

Upvotes: 2

Related Questions