Syndicated feed for Java

Weblogs: Java

Development of Java and J2EE applications, including web applications


Tuesday, January 04, 2005

Creating a java.util.Date object using GregorianCalendar

Given three primitive integers representing day, month and year and constructing a java.util.Date object used to be so easy in the JDK 1.0 days. But now the setDay(), setMonth(), and setYear() methods have been deprecated in favour of using Calendar object - presumably to incorporate the various calendaring systems around the world.

Looking through the JDK 1.3.1 specification shows two valid constructors for a Date object: a default constructor, and one that takes a timestamp in milliseconds. Obviously any Calendar object needs to be able to convert a date into a timestamp so we can properly instantiate a Date object - this is done by the getTime() method.

Here's the barebones code needed to convert three integers (stored as Strings) into a valid Date object. Note the data is not validated at this point - my application has already checked the validity of the data right up in the Struts ActionForm. Also months in Java run from 0 through to 11, requiring a -1 on the month parameter.


 String year  = "2004";
 String month = "12";
 String day   = "31";

 GregorianCalendar newGregCal = new GregorianCalendar(
     Integer.parseInt(year),
     Integer.parseInt(month) - 1,
     Integer.parseInt(day)
 );
 Date newDate = new Date(newGregCal.getTime());

The above code looks easy enough, but its a devil of a job getting the code down to something as simple as this.


[ Weblog | Categories and feeds | 2011 | 2010 | 2009 | 2008 | 2007 | 2006 | 2005 | 2004 | 2003 | 2002 ]