how to create a Date object using the Calendar class
Previous | Home | Next |
In this example we are going to create a Date object using Calendar class.
For using the class Calendar, firstly we have to import the java.util package which contains the java.util.Calendar class in which contains various definitions and methods which can be applied on the Calendar object. In the following example we have created a class named CollectionExample in which we have created an instance of Calendar and defined various methods.
In this example we have used the following method of the Calendar class,
static Calendar getInstance()
This method gets a calendar using the default time zone and locale.
void clear()
The above method sets all the calendar field values and the time value of the current Calendar to undefined.
void set(int calendarfield, int fieldval)
This method sets the given calendarfield to the given fieldvalue.
Date getTime()
The above method returns a Date object representing the current calendar time values.
In this example we have created a Calendar instance and instantiated it by using the getInstance method and displayed the current time and date. Then we have clear all the Calendar fields by using the clear() mthod on the object of the Calendar i.e clndr( in this example).
We again set the Calendar values by using the set(int calendarfield, int fieldvalue) method on the Calendar object. We have also created a Date object date and by using the Calendar's instance clndr and by invoking the getTime() method on it we have stored the desired date values to the Date object.
Finally we have displayed the date values.
package r4r.co.in;
import java.util.*;
public class CollectionExample
{
/**
* @param args
*/
public static void main(String args[])
{
int year=2009; // defining a variable named year
int month=7; // defining a variable name month of int type
int day=7; // defining a variable named day of int type
Calendar clndr=Calendar.getInstance(); // getting the calendar instance
System.out.println("The current time is given as: "+clndr.getTime()); // displaying the time
clndr.clear(); // clearing all the fields of the calendar
System.out.println("The current time is given as: "+clndr.getTime()); // now again displaying the time
clndr.set(Calendar.YEAR, year); // setting the YEAR field of calendar to year
clndr.set(Calendar.MONTH, month); // setting the MONTH field of calendar to month
clndr.set(Calendar.DAY_OF_MONTH, day); // setting the DAY field of calendar to day
Date date=clndr.getTime(); // creating the Date instance and storing the value of clndr.getTime() in it
System.out.println("Now the date is represented as: "+date); // displaying the date
}
}
The output of the above example is given below:
The current time is given as: Mon Nov 15 18:28:13 PST 2010
The current time is given as: Thu Jan 01 00:00:00 PST 1970
Now the date is represented as: Fri Aug 07 00:00:00 PDT 2009
Previous | Home | Next |