Saturday, August 15, 2009

Convert Calendar to Date

In one of the previous, date to calendar conversion was discussed. Following is the program to convert a Calendar (java.util.Calendar) object to Date (java.util.Date) object. The program can easily be understood by looking at the comments. You can even test drive the program directly.

Conversion from Calendar to Date is pretty easy:
1. given a calendar object, you just need to use the getTime() methos available in calendar class as the following:
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
That's it.

package com.blog.javaexposure.util;

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

public class Calendar2Date {
public static void main(String[] rags){
//get the current date as Calendar object
Calendar cal = Calendar.getInstance();
// returns the date object represented by Calendar object
Date date = cal.getTime();
System.out.println("Current date using \n calendar object: "+cal);
System.out.println("date object: "+date);
// if you want to a get tomorrow's date and calendar object, do the following
cal.add(Calendar.DATE, 1);
date = cal.getTime();
System.out.println("Tomorrows date using \n calendar object: "+cal);
System.out.println("date object: "+date);
}
}

Note: Wheh you look at the calendar object value in the output, you see all properties of the calendar object.

1 comment:

  1. Excellent post, but its important to remember that SimpleDateFormat is not a thread-safe class and requires external synchronization in Java.

    10 example of date to string in Java

    ReplyDelete

È