首页 > 解决方案 > 将一种格式的String类型的Date转换为另一种Date格式的String类型

问题描述

我有一个用例需要更改 Java 中的日期格式。输入日期将采用字符串的形式,所需的输出格式也是字符串。

Input_Date 可以是任何形式 (yyyy-MM-dd):

Output_Date 将是:

标签: javastringdatesplitdate-formatting

解决方案


两种情况:

  1. 一个日期String将被重新格式化,并且
  2. 一个String包含两个(或更多?)连接日期的单个日期,也用 & 号分隔

我将首先定义java.time.format.DateTimeFormatter创建所需输出所需的(我在这里选择了一个类常量):

public static final DateTimeFormatter FORMATTER =
                        DateTimeFormatter.ofPattern("MMMM dd,uuuu", Locale.ENGLISH);

确保向 提供 a LocaleDateTimeFormatter否则它将采用默认语言环境,这可能会以不需要的格式和语言产生输出。

第一个在 Java 8 中使用时非常直截了当java.time.LocalDate.parse(String s),因为您只需要使用之前定义的格式化程序LocalDate.format(DateTimeFormatter formatter)(代码示例如下)。

第二个需要更多处理,我认为您必须拆分输入,解析包含的每个日期,重新格式化每个日期并String使用连字符作为分隔符将结果连接到单个。

处理多日期String

public static String convertConcatDates(String concatenatedDates) {
    // split the input by ampersand first
    String[] splitInput = concatenatedDates.split("&");
    // convert all / both of the dates to LocalDates in a list
    List<LocalDate> dates = Arrays.stream(splitInput)
                                  .map(LocalDate::parse)
                                  .collect(Collectors.toList());
    // create a list of each date's month and day of month
    List<String> daysAndMonths = new ArrayList<String>();
    // get each date as formatted String
    dates.forEach(date -> daysAndMonths.add(date.format(FORMATTER)));
    // then concatenate the formatted Strings and return them as a single one
    return String.join("-", daysAndMonths);
}

main显示两种重新格式化的示例:

public static void main(String[] args) throws IOException {
    /*
     *  (1) example for a single date String
     */
    String single = "2021-08-30";
    // parse the date (no pattern needed if input is ISO standard)
    LocalDate singleLd = LocalDate.parse(single);
    // print the result in the desired format
    System.out.println(singleLd.format(FORMATTER));
    
    /*
     * (2) example for concatenated date Strings
     */
    String concat = "2021-08-30&2021-09-16";
    // call the method and print the result
    System.out.println(convertConcatDates(concat));
}

输出:

August 30,2021
August 30,2021-September 16,2021

推荐阅读