Creating java.util.date and java.util.sql objects from Calendar object

Date, time and calendar manipulation always seem to trouble average developers. Well it does for me too, sometimes. In this particular very simple tutorial, I have shown how we can create java.sql.date object and java.util.date object from Calendar object.

package com.kushal.utils.date;
import java.util.Calendar;

public class DateUsingCalendar {
	/**
	 * @param year - an integer representing the year
	 * @param month - an integer from 0-11 (Jan - Dec)
	 * @param dayOfMonth - an integer from 1-31
	 */
	public static void createDateFromCalendar(int year, int month,
			int dayOfMonth) {

		/**
		 * Creates a current calendar using
		 * the default time zone and locale.
		 */
		Calendar myCalendar = Calendar.getInstance();

		/**
		 * Resets all the attributes of calendar
		 */
		myCalendar.clear();

		/**
		 * Let's try setting our values
		 */
		myCalendar.set(Calendar.YEAR, year);
		myCalendar.set(Calendar.MONTH, month);
		myCalendar.set(Calendar.DATE, dayOfMonth);

		/**
		 * We will try creating a new sqlDate using this
		 * Calendar Object
		 */
		java.sql.Date sqlDateObj = new java.sql.Date(
				myCalendar.getTimeInMillis());

		/**
		 * We will try creating a new java util Date object
		 * using this Calendar Object
		 */
		java.util.Date utilDateObj = myCalendar.getTime();

		/**
		 * Let's try printing these dates to the console
		 */

		System.out.println("Date in sql date format: "+sqlDateObj);
		System.out.println("Date in util date format: "+utilDateObj);

	}

	public static void main(String[] args) {
		int year=2009;
		int month=5; //June (January being 0)
		int dayOfMonth=11;
		createDateFromCalendar(year, month, dayOfMonth);
	}
}

_______________________
Here is the output:
Date in sql date format: 2009-06-11
Date in util date format: Thu Jun 11 00:00:00 CDT 2009

Share
Tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply