0

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.

Community
  • 1
  • 1
Rob L
  • 3,073
  • 6
  • 31
  • 61
  • The function getTime() returns a Date object, and Date objects, when when converted to a string, are represented using [your default time zone](http://stackoverflow.com/a/31393107/300257). – Gilbert Le Blanc Jul 13 '15 at 22:24

1 Answers1

2

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));
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332