Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Dates in Java

Tags:

java

arrays

date

I know how to create an array of strings or integers, but how does one create an array of dates :/

like image 730
Madison Avatar asked Nov 26 '09 01:11

Madison


2 Answers

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 ) );
        }
    }
}
like image 108
OscarRyz Avatar answered Sep 19 '22 13:09

OscarRyz


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

like image 27
thecoop Avatar answered Sep 19 '22 13:09

thecoop