Calendar Class in java

Calendar class

  • Calendar class is useful in two ways:
    • It knowing the system date and time.
    • It helps in storing a date and time value so that it can be transported to some other application.
  • We can create object of the Calendar class as:
    Calendar cl = Calendar.getInstance();

Calendar class includes the following methods:
int get(int field)
This method returns the value of the given calendar field.
For example,
Calendar.DATE gives the date number from 1 to 31

void set(int field, int value)
This method sets the given calendar field to the given value. For example, we can set a date like 19th May 1993 to calendar object as:
cl.set(Calendar.DATE, 19);
cl.set(Calendar.MONTH, 5);
cl.set(Calendar.YEAR, 1993);

String toString()
This method returns the String representation of the Calendar object.

Boolean equals(Object obj)
This method compares the Calendar object with another object obj and returns true if they are same, otherwise false.

Write a program that shows the use of Calendar class
import java.util.*;
public class test
{
public static void main(String args[])
{
Calendar cl = Calendar.getInstance();
System.out.println(“Current Date “);
int dd=cl.get(Calendar.DATE);
int mm=cl.get(Calendar.MONTH);
++mm;
int yy=cl.get(Calendar.YEAR);
System.out.println(dd+”/”+mm+”/”+yy);
System.out.println(“Current Time “);
int h=cl.get(Calendar.HOUR);
int m=cl.get(Calendar.MINUTE);
int s=cl.get(Calendar.SECOND);
System.out.println(h+”:”+m+”:”+s);
int x=cl.get(Calendar.AM_PM);
if(x==0)
System.out.println(“Good Morning”);
else
System.out.println(“Good evening”);
}
}

Output:
Current Date
19/5/1993
Current Time
4:2:15
Good evening

Leave a Reply

Your email address will not be published. Required fields are marked *