Easy learning with example program codes

Java util calendar class


The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR etc.

Calendar class declaration:

public abstract class Calendar extends Object  implements Serializable, Cloneable, Comparable

Calendar provides a class method, getInstance which returns a Calendar object.

Calendar currentDate = Calendar.getInstance();

Java Calendar Class Methods

Method Description
abstract void add(int field, int amount) Add or subtract the specified amount of time to the given calendar field, based on the calendar’s rules.
int get(int field) Return the value of the given calendar field.
Static Calendar getInstance() Get a calendar object using the default time zone and locale.
abstract int getMaximum(int field) Return the maximum value for the given calendar field of this Calendar instance.
abstract int getMinimum(int field) Return the minimum value for the given calendar field of this Calendar instance.
void set(int field, int value) Set the given calendar field to the given value.
void setTime(Date date) Set this Calendar’s time with the given Date.
Date getTime() Return a Date object representing this Calendar’s time value. class example

package com.codesjava;
import java.util.Calendar;
public class CalenderTest {
	public static void main(String args[]){
	   Calendar calendar = Calendar.getInstance();  
	   System.out.println("The current date is : " + calendar.getTime());  
	   calendar.add(Calendar.DATE, -10);  
	   System.out.println("10 days ago: " + calendar.getTime());  
	   calendar.add(Calendar.MONTH, 3);  
	   System.out.println("3 months later: " + calendar.getTime());  
	   calendar.add(Calendar.YEAR, 4);  
	   System.out.println("4 years later: " + calendar.getTime()); 
	   int maximum = calendar.getMaximum(Calendar.DAY_OF_WEEK);  
	   System.out.println("Maximum number of days in week: " + maximum);  
	   maximum = calendar.getMaximum(Calendar.WEEK_OF_YEAR);  
	   System.out.println("Maximum number of weeks in year: " + maximum);  
	   int minimum = calendar.getMinimum(Calendar.DAY_OF_WEEK);  
	   System.out.println("Minimum number of days in week: " + minimum);  
	   minimum = calendar.getMinimum(Calendar.WEEK_OF_YEAR);  
	   System.out.println("Minimum number of weeks in year: " + minimum);  


The current date is : Mon Apr 09 19:26:10 IST 2018
10 days ago: Fri Mar 30 19:26:10 IST 2018
3 months later: Sat Jun 30 19:26:10 IST 2018
4 years later: Thu Jun 30 19:26:10 IST 2022
Maximum number of days in week: 7
Maximum number of weeks in year: 53
Minimum number of days in week: 1
Minimum number of weeks in year: 1
Posted in Date   

Copyright © 2018 CodesJava Protection Status SiteMap