Code Comments

Code Comments

Tips and short tutorials on various programming technologies

Code Comments RSS Feed
 
 
 
 

Creating Instances of Java Date Class

I have a hard time understanding why Java made it so difficult to create instances of dates, but I’m sure there was some logical reason. You would think you could use a constructor or factory method on the Date class, but this doesn’t exist or has been deprecated. So what I have been able to find to use is the Calendar class. Even still the approach they used leaves me baffled because it’s not intuitive at all (I have to look it up each time I do it, which is why I’m posting this) and takes 3 lines of code.

import java.util.*;
 
...
 
Calendar cal = Calendar.getInstance();
cal.set(2008, Calendar.OCTOBER, 1);
Date d = cal.getTime();

The Calendar and Date classes are in java.util.*. If someone knows of some better way to do this, please enlighten me.

Below are some generic methods for doing this:

import java.util.*;
 
...
 
public static Date CreateDate(int year, int month, int day)
{
    return CreateDate(year, month, year, 0, 0, 0);
}
 
public static Date CreateDate(int year, int month, int day, int hour, int minute, int second)
{
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, day, hour, minute, second);
    return cal.getTime();
}

Leave a Reply