Java Programming | The Calendar Tutorial and Example

Introduction.

This is a tutorial for the Calendar(java.util.Calendar) in java. This is very useful and has lots of applications. So learning this is very beneficial. So Lets Begin….

Program for Calendar in Java.

//import Calendar as we require them.
import java.util.Calendar;
 
// the name of our class its public
public class CalendarExample {
    //void main
        public static void main (String[] args)
        {
            //declare the Calendar obj.
            Calendar calendar = Calendar.getInstance();
 
            //get the dat in int variables.
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);
 
            //print them.
            System.out.println(calendar.getTime());
            System.out.println("year: " + year);
            System.out.println("month: " + month);
            System.out.println("day: " + day);
        }
}

Output

Sat Nov 23 18:44:46 IST 2013
year: 2013
month: 10
day: 23

How does it work

  1. Nothing to input the date and time is directly printed.

Extending it

The program can be extended. This is a basic concept of java programming and has lots of applications. I have limited the program to only 4 things. You can use others:-

  • Calendar.DAY_OF_WEEK.
  • Calendar.WEEK_OF_YEAR.
  • Calendar.WEEK_OF_MONTH.
  • Calendar.HOUR.
  • Calendar.MINUTE.
  • Calendar.SECOND.
  • Calendar.MILLISECOND.

Explanation.

  1. Import the Calendar.
  2. Declare the class as public
  3. Add the void main function
  4. Declare Calendar object.
  5. Get the Data and Save it in variables.
  6. Add system.out.println() function to print the data.

At the end.

You learnt creating the Java program for Calendar. So now enjoy the program.

Please comment on the post and share it.

Sharing options: