1

I am simply creating a java.util.GregorianCalender

GregorianCalendar calender = new GregorianCalendar();

now setting the hour,min,sec and ms as follows

c.set(Calendar.HOUR, 6);
c.set(Calendar.MINUTE, 45); 
c.set(Calendar.SECOND, 30);         
c.set(Calendar.MILLISECOND, 345);

now printing the output using getTime() method

System.out.println("Date and Time: "+c.getTime());

When System time is in AM, the output is

Date and Time: Tue Feb 09 06:45:23 IST 2016

And When System time is in PM, the output is

Date and Time: Tue Feb 09 18:45:23 IST 2016

Now my question is why the output is changing with the system time?

Tanmoy Banerjee
  • 1,433
  • 3
  • 22
  • 31

1 Answers1

2

new GregorianCalendar() fields are set using the current time in your default time zone. The AM/PM flag is therefore set depending on whether the current time in your default time zone is AM or PM.

When you set HOUR to 6, the AM/PM flag is not changed and the resulting calendar is set on 6am or 6pm depending on the current time.

If you set HOUR_OF_DAY to 6, the calendar will be set on 6am, regardless of current time.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • thanks for your explanation. Now I understand it. Could you please tell me if we set HOUR to 18(i,e greater than 11), then what is the expected behavior? – Tanmoy Banerjee Feb 09 '16 at 11:55
  • I don't think it is well defined but looking at the implementation it will use 18 as hour of day and add 12 if the AM/PM flag is on set to PM (resulting in 6AM the day after). – assylias Feb 09 '16 at 12:16
  • if it will use 18 as hour of day then why the question of AM/PM is coming? – Tanmoy Banerjee Feb 09 '16 at 12:37
  • Sorry I meant hour. Hour = 18 => hour of day = 18 + PM?12:0; => 30 if PM => 6am the next day. If that makes sense... But that seems to be an abuse of the API... – assylias Feb 09 '16 at 12:58