java - 将一种格式的String类型的Date转换为另一种Date格式的String类型
问题描述
我有一个用例需要更改 Java 中的日期格式。输入日期将采用字符串的形式,所需的输出格式也是字符串。
Input_Date 可以是任何形式 (yyyy-MM-dd):
- 2021-08-30&2021-09-16
- 2021-08-30
Output_Date 将是:
- 2021年8月30日-2021年9月16日
- 2021年8月30日
解决方案
两种情况:
- 一个日期
String
将被重新格式化,并且 - 一个
String
包含两个(或更多?)连接日期的单个日期,也用 & 号分隔
我将首先定义java.time.format.DateTimeFormatter
创建所需输出所需的(我在这里选择了一个类常量):
public static final DateTimeFormatter FORMATTER =
DateTimeFormatter.ofPattern("MMMM dd,uuuu", Locale.ENGLISH);
确保向 提供 a Locale
,DateTimeFormatter
否则它将采用默认语言环境,这可能会以不需要的格式和语言产生输出。
第一个在 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
推荐阅读
- c# - 无法加载实体框架不变名称“MySql.Data.MySqlClient”
- python - 使用 CSV 数据文件 Sklearn 的简单线性回归
- java - 'overridden method does not throw Exception' when use lambda with override exception thrown
- java - 使用 POI 库时出现 ClassNotFoundException org.apache.commons.collections4.ListValuedMap
- java - 如何通过 Selenium 访问框架内的嵌套 html
- php - phpmailer无法发送电子邮件
- haskell - I think there is a type mismatch in default definition in instance Applicative Maybe in Haskell
- python - 如何用python进行离散优化
- gcc - 为什么在Makefile中的`-L`之后`-R`
- google-sheets - 带有逻辑语句的 Google 表格查询