格式化 org.joda.time.LocalDate

formatting the org.joda.time.LocalDate

我正在处理 java 应用程序。我正在将 LocalDates 列表转换为字符串数组。当我打印字符串数组时,我应该得到格式化的日期。

现在的日期格式是2016-10-12, 2016-10-13..我想格式化成October 12,2016 October 13,2016... 我尝试使用不同的方法,但这在格式化方法附近给我带来了错误。请建议如何将日期格式化为 2016 年 10 月 12 日......并存储在字符串数组中。 下面是我的代码:

   // 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);
                          }
               } }

输出:

2016-10-12

2016-10-13

2016-10-14

2016-11-12

2016-12-12

我想格式化日期从2016-10-12,2016-10-13到October 12,2016,October 13,2016..

我尝试使用 DateTimeFormatter,但是当我使用下面的代码时抛出错误,无法识别方法 parseLocalDate。

我尝试了下面的代码,但无法识别 parseLocalDate(..) 方法。

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

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

在您的代码中,您应该尝试:

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

这会打印:

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

进口:

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

试试这个,稍微重构你的代码,添加格式和解析

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

    List<String> dateStrings = new ArrayList<>(localDatesList.size());
    for (LocalDate date : localDatesList) {
        dateStrings.add(date.toString(format)); //format
    }

    System.out.println("Strings " + dateStrings);

    List<LocalDate> localDates = new ArrayList<>();
    for (String dateString : dateStrings) {
        localDates.add(formatter.parseLocalDate(dateString)); //parse
    }

    System.out.println("LocalDates " + localDates);

输出

Strings [October 13,2016, October 14,2016, October 15,2016, November 13,2016, December 13,2016]
LocalDates [2016-10-13, 2016-10-14, 2016-10-15, 2016-11-13, 2016-12-13]