Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Creating an Array of Dates

Does anyone know if there is a way to create an array of dates in the same line of code?

Date hiredDate[] = { new Date(105, 2, 15), new Date(99, 7, 26) };

Works find in J#, but will not work with Java SDK 1.4 (or atleast with the version I have).

When I compile it, I receive the following messege (and nothing works):
Note: F:\Project1Tester.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

Tool completed successfully
[502 byte] By [MrComputerWhiz] at [2007-11-11 10:19:00]
# 1 Re: Creating an Array of Dates
That's because as per the Java API documentation for Date (http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html), the constructor Date(int year, int month, int day) is deprecated (that means marked as obsolete and might be removed from future releases). There is also a relevant comment in the documentation, which is the way you should do it.

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
aniseed at 2007-11-11 22:31:41 >
# 2 Re: Creating an Array of Dates
Thank you aniseed.

Using the Calendar methods does work, but requires me to set the date first, then I can set the array value from the Calendar object. (Currently, that is what the program does do).

aCalendar.set(2005, Calendar.MARCH, 15);
hiredDate[0] = aCalendar.getTime();

aCalendar.set(1999, Calendar.AUGUST, 26);
hiredDate[1] = aCalendar.getTime();

aCalendar.set(1957, Calendar.JANUARY, 5);
hiredDate[2] = aCalendar.getTime();

But, what I was wondering, is there a way to create the array (of dates) and set its values in a single line of code. Something like this?

Date hiredDate[] = { new Date(105, 2, 15), new Date(99, 7, 26), new Date(57, 0, 5) };
MrComputerWhiz at 2007-11-11 22:32:41 >
# 3 Re: Creating an Array of Dates
make the Date class by yourself and write all the methods for it =D

or make a method that sets the date to a certain time and return the date for it
like:

private static getDate(int year, int month, int day){
aCalendar.set(year, month, day);
return aCalender.getTime();
}

whatever aCalender is...

and then do

Date hiredDate[] = { getDate(1999, Calender.AUGUST, 26), };
skyuzo at 2007-11-11 22:33:45 >
# 4 Re: Creating an Array of Dates
Thank you skyuzo,

That seems to do the trick (short of the typo... Got to love computers. the aCalender.getTime() should have been aCalendar.getTime())

And aCalendar is just an instance of the Java Clendar class.

private static getDate(int year, int month, int day)
{
aCalendar.set(year, month, day);
return aCalendar.getTime();
}
MrComputerWhiz at 2007-11-11 22:34:45 >