1

In the below code, i m trying to get dateformat for timezone PST, but i didnt get the expected output. But, If I uncomment the 2 lines (setDefault timezone), i m getting the expected results.

Do you have any good option?

    System.out.println("TimeZone.getDefault():"+TimeZone.getDefault()); // CST
   //TimeZone.setDefault(TimeZone.getTimeZone("PST"));
    Calendar cal = java.util.Calendar.getInstance(SimpleTimeZone.getTimeZone("PST"));
  //Calendar cal = java.util.Calendar.getInstance();
    Date c = cal.getTime();
    String out = new java.text.SimpleDateFormat("MMMMMddyyyy").format(c);
    System.out.println("out:"+out);

If the current date in CST is February082015 (at night 12 to 2 AM), then the expected output for PST would be February072015 (PST is 2hrs behind CST). But, I m getting the output as February082015.

2
  • What is the expected result? What is the result you are getting? Commented Feb 8, 2015 at 5:22
  • If the current date in CST is February082015 (at night 12 to 1 AM), then the expected output for PST would be February072015 (PST is 2hrs behind CST). But, I m getting the output as February082015. Commented Feb 8, 2015 at 5:25

1 Answer 1

1

Your DateFormat doesn't inherit a TimeZone from the Calender. To demonstrate, I've added a Z (which will display the time-zone offset). Run it with and without setting the TimeZone and your observed behavior is explained

DateFormat df = new SimpleDateFormat("MMMMMddyyyy Z"); // <-- The Z is TZ
df.setTimeZone(SimpleTimeZone.getTimeZone("PST")); // <-- Add/Remove this
String out = df.format(c);
Sign up to request clarification or add additional context in comments.

5 Comments

Thx for the reply. Actually, I don't want to change the format. I m getting "out:February082015 -0600" as output if i run the above.
That is PST. Remove the Z then.
I didn't notice the timezone set at the dateformat object.
Thank you.!! Its working., SimpleDateFormat df = new java.text.SimpleDateFormat("MMMMMddyyyy"); df.setTimeZone(SimpleTimeZone.getTimeZone("PST")); System.out.println("out:"+df.format(c));
There's no need to use the full package name on the right hand side of the df assignment. Also, I recommend that you prefer the DateFormat interface on the left hand side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.