joan joan - 1 month ago 17
Java Question

formatting the org.joda.time.LocalDate

I am working on java application. I am converting List of LocalDates to String array. When I print the String array I should get the formatted date.

Current date format is 2016-10-12, 2016-10-13.. I want to format it to October 12,2016 October 13,2016…
I tried using different approaches but that is throwing me error near formatting method. Please advice how to format the date to October 12,2016..and store in String array.
Below is my code:

// import org.joda.time.LocalDate;
List<LocalDate> localDatesList = new ArrayList<LocalDate>();
localDatesList.add(new LocalDate());
localDatesList.add(new LocalDate().plusDays(1));
localDatesList.add(new LocalDate().plusDays(2));
localDatesList.add(new LocalDate().plusMonths(1));
localDatesList.add(new LocalDate().plusMonths(2));
List<String> tempDatesList = new ArrayList(localDatesList.size());
for (LocalDate date : localDatesList) {
tempDatesList.add(date.toString());
}
String[] formattedDates = tempDatesList.toArray(new String[localDatesList.size()]);
for(String dates : formattedDates){
System.out.println(dates);
}
} }


Ouput:

2016-10-12

2016-10-13

2016-10-14

2016-11-12

2016-12-12

I want to format the date from 2016-10-12,2016-10-13 to October 12,2016,October 13,2016..

I tried using DateTimeFormatter, but when i'm using the below code its throwing error , could not recognize the method parseLocalDate.

I tried the below code, but unable to recognize parseLocalDate(..) method.

final DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM dd,YYYY");

final LocalDate local = formatter.parseLocalDate(date.toString());

Answer

In your code you should try :

    for (LocalDate date : localDatesList) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM dd,YYYY");          
        String str = formatter.print(date);
        System.out.println(str);
        tempDatesList.add(str);
    }

This prints :

October 13,2016
October 14,2016
October 15,2016
November 13,2016
December 13,2016

Imports :

import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
Comments