Java Calendar class
The Calendar class is an abstract class that provides a set of methods and calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on.The java.util.Calendar class is used to get date and time arithmetic.The reason is that there are more than one calendar in the world. GregorianCalendar using in java.Java support Gregorian calendar implementation,
the java.util.GregorianCalendar class.
Syntax:
Calendar ca = new GregorianCalendar();
Calender properties (TO get):
Calendar ca = new GregorianCalendar();
int year = ca.get(Calendar.YEAR);
int month = ca.get(Calendar.MONTH);
int day = ca.get(Calendar.DAY_OF_MONTH); // If Jan = 0, not 1
int dayOfWeek = ca.get(Calendar.DAY_OF_WEEK);
int weekOfMonth = ca.get(Calendar.WEEK_OF_MONTH);
int weekOfYear = ca.get(Calendar.WEEK_OF_YEAR);
int hourOfDay = ca.get(Calendar.HOUR_OF_DAY); // 24 hour clock format
int hour = ca.get(Calendar.HOUR); // 12 hour clock format
int minute = ca.get(Calendar.MINUTE);
int second = ca.get(Calendar.SECOND);
int millisecond = ca.get(Calendar.MILLISECOND);
Calender properties (To set):
Calendar ca = new GregorianCalendar();
ca.set(Calendar.DAY_OF_MONTH, 14);
ca.set(Calendar.MONTH, 1); // 1 = FEBRUARY month
ca.set(Calendar.YEAR, 2014);
Java Calender class program:
import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendorDemo {
public static void main(String[] args) {
Calendar ca = new GregorianCalendar();
System.out.println(ca.get(Calendar.DATE));
System.out.println(ca.get(Calendar.SATURDAY));
System.out.println(ca.get(Calendar.FRIDAY));
System.out.println(ca.get(Calendar.WEDNESDAY));
System.out.println(ca.get(Calendar.FEBRUARY));
System.out.println(ca.get(Calendar.AM));
System.out.println(ca.get(Calendar.PM));
System.out.println(ca.get(Calendar.AM_PM));
System.out.println(ca.get(Calendar.PM));
System.out.println(ca.get(Calendar.HOUR));
System.out.println("*********************");
ca.set(2014, 05, 20); //set calendar properties
System.out.println(ca.get(Calendar.DATE));
System.out.println(ca.get(Calendar.MONTH));
System.out.println(ca.get(Calendar.HOUR));
}
}
Interview Questions:
What a sample java program to get default to get year and month and date?
Which calendar java supports?
Write few calendar get and set properties?
Which class we need to import to get default calendar?
2 comments
Very nice tutorial buddy
Thank you... @naresh etikyala
EmoticonEmoticon