4

My problem can be easily created by the scenario below:

 //create a gregorian calendar object that set the date and time as 4th June 2012 at 10:30PM
 Calendar calendar = new GregorianCalendar(2012, 6, 4, 22, 30);

 //when I print out these:
 System.out.println(calendar.get(Calendar.DAY_OF_WEEK));
 System.out.println(calendar.get(Calendar.MINUTE));
 System.out.println(calendar.get(Calendar.HOUR));
 System.out.println(calendar.get(Calendar.DATE));
 System.out.println(calendar.get(Calendar.MONTH));
 System.out.println(calendar.get(Calendar.YEAR));

 //output reads as:
 4
 30
 10
 4
 6
 2012

 //so does calendar.get(Calendar.DAY_OF_WEEK) == calendar.get(Calendar.DATE) ???

Just so that everyone is clear the 4th of June 2012 is a Monday, so shouldn't calendar.get(Calendar.DAY_OF_WEEK) return 0 as part of the first day of the week?

Thank for your all your help and concerns, please also verify the source that you are referring to.

user1442080

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
user1442080
  • 41
  • 1
  • 1
  • 2

2 Answers2

8

The month in java Calendar classes is 0-based. So June is month number 5.

You actually created an object representing July 4th, which happens to be a Wednesday, which is the fourth day of that week.

Malady
  • 251
  • 1
  • 12
Kees de Kooter
  • 7,078
  • 5
  • 38
  • 45
  • THANK YOU! I also noticed the date starts from 0 as well. So I actually created an object that represented July 5th. – user1442080 Jun 07 '12 at 13:47
  • My pleasure. You could also take a look at a more intuitive time library: http://joda-time.sourceforge.net/. (Oh and would you be so kind as to accept my answer ;-)) – Kees de Kooter Jun 07 '12 at 18:34
4

One should always look for values returned by Calendar.{field} e.g. like Calendar.SUNDAY, Calendar.MONDAY, Calendar.JANUARY, Calendar.MARCH etc. and so on. This is because, the values returned by Calendar.{field} depends upon the TimeZone specified while creating Calendar instance. You can try this by creating two calendar instances with different timezones:

Calendar.getInstance("BST")

and

Calendar.getInstance() // default timezone

and now try getting calendar.get(Calendar.DAY_OF_WEEK) which will return different integer values for these two instances.

Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62
  • How would calendar.get(Calendar.DAY_OF_WEEK) return different integer values? The day of the week values are constants, you still have to compare the return value of DAY_OF_WEEK to Calendar.FRIDAY (for example). The value of the first day of the week might change based upon timezone, but the values returned by DAY_OF_WEEK will always need to line up with the java calendar constants. – John Bowers Jul 11 '14 at 14:04