The returned time and date are correct except for the hour, which is 1 hour less than it should be.
It seems I am setting everything that is required to get the correct time and date:
- I'm using Calendar.getInstance(), instead of new Date() - I'm setting the timezone of the Calendar instance with Timezone.getTimeZone - I'm using DateFormat and SimpleDateFormat to format the output
My time zone is Eastern Standard Time , aka UTC/GMT-5:00 . None of these lines have any effect:
- cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName())); - cal.setTimeZone(TimeZone.getTimeZone("EST")); - cal.setTimeZone(TimeZone.getTimeZone("UTC")); - cal.setTimeZone(TimeZone.getTimeZone("GMT")); - cal.setTimeZone(TimeZone.getTimeZone("GMT-5:00"));
... but each of these options sets my desired time zone.
Here is my attempt when I mistakenly add 1 hour to a
Calendar instance:
PrintWriter output = null; try { output = new PrintWriter( new BufferedWriter(new FileWriter("output.txt", true))); DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:ms MM/dd/yyyy"); Calendar cal = Calendar.getInstance(); // ...doesn't seem to be working: cal.setTimeZone(TimeZone.getTimeZone(cal.getTimeZone().getDisplayName())); /* * adding an extra hour here, to make up for the incorrect hour value??? * ...without this line, everything is correct except the hour = n - 1: */ //cal.setTimeInMillis(cal.getTimeInMillis() + (1000 * 60 * 60)); // printing to console here: System.out.println(dateFormat.format(cal.getTime())); System.out.println(cal.getTimeZone().getDisplayName()); // printing to the log-file here: output.println(dateFormat.format(cal.getTime())); output.println(cal.getTimeZone().getDisplayName()); } catch (IOException e) { e.printStackTrace(); } finally { if (output != null) { output.close(); } }
Exit:
10:05:43:543 10/10/2013 GMT-05:00
WRONG - it should be 11:05:43:543 ! (ps - Sorry, I can't use Joda-Time )
java timezone datetime calendar
Ian campbell
source share