Shawn Shawn - 3 months ago 7
Java Question

Date time String + TimeZone

I have a String representation of a local date time, and a Java TimeZone.

I am trying to get output in the format MM/dd/yyyy HH:mm:ssZ but I can't figure out how to create a Calendar or JodaTime object with the correct date time and timezone. How do you get a TimeZone converted to a value that can be parsed by SimpleDateFormat 'Z' or 'z'?

TimeZone tz = TimeZone.getTimeZone("America/Chicago");
String startDate = "08/14/2014 15:00:00";

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance(tz);
cal.setTime(sdf.parse(startDate));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ");


and

sdfZ.format(cal.getTime())


returns

08/14/2014 15:00:00-0400


which is
EST
.

Is the only workaround to create a Calendar or Joda DateTime and set the individual year/month/day/hour/min values by parsing the string "08/14/2014 15:00:00" ?

Answer

Calendar getTime() - Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(01-01-1970 00:00 GMT)") irrespective of which timezone you are displaying. But hour of day in different TimeZone will be different. get(Calendar.HOUR_OF_DAY)

You should try

sdfZ.setTimeZone(tz);
Comments