I know how to create an array of strings or integers, but how does one create an array of dates :/
The same way you do for String and Int , you just place different types inside:
Date [] dates = {
new Date(),
new Date()
};
Declared an array of size two with two dates.
You can also initialize with null values:
Date [] dates = new Date[2];
Or add more significant values:
Date [] dates = {
getDateFromString("25/11/2009"),
getDateFromString("24/12/2009")
};
....
public Date getDateFromString( String s ) {
Date result = ...// parse the string set the value etc.
return result;
}
EDIT
...but is there anyway you can finish up what you were doing in the getDateFromString method?
Sure, I didn't initially because my point was to show, that you could put anything that is of type "Date" there.
You just have to use the SimpleDateFormate.parse() method ( inherited from DateFormat class )
simpleDateFormatInstance.parse( "24/12/2009" ); // returns christmas 2009.
Here's a complete working sample:
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import static java.lang.System.out;
public class DateArrayTest {
private static final SimpleDateFormat dateFormat
= new SimpleDateFormat("dd/MM/yyyy");
private static final Date invalidDate = new Date(0);
// test creating a date from a string.
public static void main( String [] args ) {
Date [] randomDates = {
fromString("01/01/2010"), // new year
fromString("16/09/2010"), // 200 yrs Mex indepence
fromString("21/03/2010"), // uhhmm next spring?
fromString("this/should/fail"), // invalid date.
};
for( Date date: randomDates ) {
print( date );
}
}
/**
* Creates a date from the given string spec.
* The date format must be dd/MM/yyyy ie.
* 24 december 2009 would be: 24/12/2009
* @return invalidDate if the format is invalid.
*/
private static final Date fromString( String spec ) {
try {
return dateFormat.parse( spec );
} catch( ParseException dfe ) {
return invalidDate;
}
}
private static final void print( Date date ) {
if( date == invalidDate ) {
out.println("Invalid date");
} else {
out.println( dateFormat.format( date ) );
}
}
}
you can use an array of java.util.Date
(API docs are here)
Date[] dates = new Date[] {
new Date(),
new Date(),
};
You can create an array of any object type in java - all reference and primitive types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With