Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #6
See Also: JBuilder Papers

Date and Calendar classes: Month zero
Yes, you read it right: in Java we have got the month 0 (zero). It sounds strange, and it is strange, but we have to live with it. Java provides basically two date classes, we can use when working with dates in our programs. First the java.util.Date class, with a lot of deprecated methods since Java 1.1. And secondly the java.util.Calendar class. This class contains a lot of useful constants and methods to work with dates.

But both contain the mentioned month zero. In these classes months are counted from 0 to 11, for January to December. So if we ask which month number July is, the methods in the Date and Calendar classes will return 6 instead of 7. Therefore if you want to use months, it is best to use the constants in the Calendar class, to set and change the month.

For example we want to create a Calendar object, and set the month to July, by first using 7 to set the month and then using the constant for July in the Calendar class. We can use the following code for this:

  /*
   * Create Calendar object
   */
  java.util.Calendar myCalendar = java.util.Calendar.getInstance();

  /*
   * Set the month to the 7th month (should by July, right?)
   */
  myCalendar.set(java.util.Calendar.MONTH, 7);

  /*
   * Create SimpleDateFormat object to format the date so we can show it.
   * This object will show the name of the month (the MMM parameter).
   */
  java.text.SimpleDateFormat dateFormatter = new java.text.SimpleDateFormat("MMM");
  String date = dateFormatter.format(myCalendar.getTime());

  /*
   * Output formatted date to System.out
   */
  System.out.println("Date? " + date);

  /*
   * Creating another Calendar object
   */
  java.util.Calendar myOtherCalendar = java.util.Calendar.getInstance();

  /*
   * Set the month to July by using the constants Calendar.JULY
   */
  myOtherCalendar.set(java.util.Calendar.MONTH, java.util.Calendar.JULY);

  /*
   * Format date and send it to System.out
   */
  date = dateFormatter.format(myOtherCalendar.getTime());
  System.out.println("Date? " + date);

When we execute this code, the result will be:

  Date? Aug
  Date? Jul

So keep this in mind when you are using the mentioned classes in your programming!


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.