Monday, August 10, 2009

Convert Date to Calendar

Convert date to calendar:

Both Date and Calendar are availabel in java.util package. Date object represents the
specific instant of time. Calendar class is an abstract calss used for converting
between a Date object and a set of integer fields.. YEAR, MONTH,DAY, HOUR...etc.

Following example program converts a Date object into Calendar object.

This is achieved in the following steps:
1. getting the calendar instance.
Calendar cal = Calendar.getInstance();
2. getting the date object which you want to convert to Calendar object.
Assuming that we are going to convert the current date into calendar object,
Date d = new Date();
3. use the setTime(date) method available in Calendar class to convert the date to calendar object.
cal.setTime(d);

import java.util.Date;
import java.util.Calendar;

public class Date2Calendar {
public static void main(String[] rags){
Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date)
System.out.println("Current date is:"+cal);
}
}

1 comment:

  1. Good post mate, but its important to remember that SimpleDateFormat is not a thread-safe class and requires external synchronization in Java. you can check 10 example of date to string in Java for date to string conversion.

    Thanks
    Javin
    Java Generics Tutorial: How to use Generics in Java

    ReplyDelete

È