从yyyy-MM-dd hh:mm:ss格式格式化日期 [英] Format date in yyyy-MM-dd hh:mm:ss format from whatever format
本文介绍了从yyyy-MM-dd hh:mm:ss格式格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有各种日期字符串,并且想要使用java格式化为特定格式
I am having various date String and want to format in particular format using java
String arr[] = {"Jul 02,2020 ","15-10-2015 10:20:56","2015/10/26 12:10:39","27-04-2016 10:22:56","April 7, 2020"};
Arrays.asList(arr).forEach(date->{
try {
System.out.println(convertDate(date, "yyyy-MM-dd hh:mm:ss"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
public static String getDateString(String date,String patternStr) throws ParseException {
if(StringUtils.isNotEmpty(date)&& StringUtils.isNotEmpty(patternStr)) {
SimpleDateFormat pattern = new SimpleDateFormat(patternStr);
Date dateObject =new Date(date);
return pattern.format(dateObject).toString();
}
return date;
}
但是我正在解析某些日期值的Exception。是否有任何通用的支持方式对于所有输入日期值
。
But i am getting parse Exception for some of the date value.Is there any generic way to support for all the input date value
.
推荐答案
我建议您从过时且容易出错的 java.util
日期时间API到丰富的现代日期时间API集。使用 DateTimeFormatterBuilder
,您可以构建一个格式,其中包括所有预期的日期时间格式以及时,分,秒,默认为 0
I recommend you switch from the outdated and error-prone java.util
date-time API to the rich set of modern date-time API. Using DateTimeFormatterBuilder
, you can build a format including all expected date-time formats and hour, minute, second defaulting to 0
.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class Main {
public static void main(final String[] args) {
String arr[] = { "Jul 02,2020 ", "15-10-2015 10:20:56", "2015/10/26 12:10:39", "27-04-2016 10:22:56",
"April 7, 2020" };
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("[MMM d,yyyy]")
.appendPattern("[dd-MM-yyyy HH:mm:ss]")
.appendPattern("[yyyy/MM/dd HH:mm:ss]")
.appendPattern("[dd-MM-yyyy HH:mm:ss]")
.appendPattern("[MMMM d, yyyy]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
for (String s : arr) {
LocalDateTime ldt = LocalDateTime.parse(s.trim(), formatter);
System.out.println("LocalDate#toString: " + ldt + ", " + "Formatted: "
+ ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
}
输出:
LocalDate#toString: 2020-07-02T00:00, Formatted: 2020-07-02 00:00:00
LocalDate#toString: 2015-10-15T10:20:56, Formatted: 2015-10-15 10:20:56
LocalDate#toString: 2015-10-26T12:10:39, Formatted: 2015-10-26 12:10:39
LocalDate#toString: 2016-04-27T10:22:56, Formatted: 2016-04-27 10:22:56
LocalDate#toString: 2020-04-07T00:00, Formatted: 2020-04-07 00:00:00
这篇关于从yyyy-MM-dd hh:mm:ss格式格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文