简体   繁体   中英

How to Convert String into Date Java

I currently have an ArrayList filled with dates in the format 2012-06-19 and I am trying to add them all to an array of Date s.

This is the portion of code that is failing me,

    listIterator = dateValues.listIterator();

    Date [] dates = new Date[dateValues.size()];
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    int i = 0;
    try{
        while(listIterator.hasNext())
        {
            //System.out.println(listIterator.next().toString());
            dates[i] =  dateFormat.parse(listIterator.next().toString());
            i++;

        }

        for(i = 0; i < dates.length;i++)
        {
            System.out.println(dates[i]);
        }
    }
    catch(Exception e){e.printStackTrace()};
}

The line

//System.out.println(listIterator.next().toString());

will print out every date in the ArrayList. Output looks like,

2007-09-07
2007-09-07
2007-10-05
2007-10-05
2007-10-05
2007-10-05
2007-10-05

but my dateFormat line never adds any values to dates[] . Any help would be appreciated.

And no, it isn't homework.

Try this:

List<String> dateValues = new ArrayList<String>();
Date[] dates = new Date[dateValues.size()];
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
int i = 0;
for (String dateValue : dateValues) {
    dates[i++] = dateFormat.parse(dateValue);
}

"Less code is good", so use the language (foreach loops etc) to keep your code small and clean (like the code above).

Note to pedants before you comment: "less code is good", as long as it remains readable.

If the line:

//System.out.println(listIterator.next().toString()); 

is uncommented next() is called twice in a single iteration, which will eventually result in NoSuchElementException being thrown. Meaning that the subsequent for loop will not be executed. Store the result of next() :

while(listIterator.hasNext())
{
    String s = listIterator.next().toString();
    System.out.println(s);
    dates[i] = dateFormat.parse(s);
    i++;
}

Solution by @Tom Celic, works for me.

List<String> dateValues = new ArrayList<String>();
    dateValues.add("2012-09-08");
    dateValues.add("2011-09-08");
    Date[] dates = new Date[dateValues.size()];
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    int i = 0;
    for (String dateValue : dateValues) {
        dates[i++] = dateFormat.parse(dateValue);
    }
    System.out.println(dates.length);
    System.out.println(dates[0]);
    System.out.println(dates[1]);

It prints:

    2
Sat Sep 08 00:00:00 IST 2012
Thu Sep 08 00:00:00 IST 2011

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM