Java-多种方案的日期格式 [英] Java - Date format for Multiple Scenarios
本文介绍了Java-多种方案的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Java组件来格式化我检索的日期。这是我的代码:
I have a java component to format the date that I retrieve. Here is my code:
Format formatter = new SimpleDateFormat("yyyyMMdd");
String s = "2019-04-23 06:57:00.0";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.S");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("Formatter: "+formatter.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
只要String的格式为<$ c,代码就可以很好地工作$ c> 2019-04-23 06:57:00.0;
The code works great as long as the String s has the format "2019-04-23 06:57:00.0";
我的问题是,如何调整此代码,以便适用于以下情况,例如,
我的 s
字符串可能具有
My Question is, how to tweak this code so it will work for below scenarios ex,
my s
string may have values like
String s = "2019-04-23 06:57:00.0";
or
String s = "2019-04-23 06:57:00";
Or
String s = "2019-04-23";
现在,如果我没有通过短信,它将失败。.谢谢!
right now it fails if I don't pass the ms.. Thanks!
推荐答案
如果模式中有可选部件,则可以使用 [
和]
。
In case of you have optional parts in pattern you can use [
and ]
.
例如
public static Instant toInstant(final String timeStr){
final DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH[:mm[:ss[ SSSSSSSS]]]")
.withZone(ZoneId.of("UTC"));
try {
return Instant.from(formatter.parse(timeStr));
}catch (DateTimeException e){
final DateTimeFormatter formatter2 = DateTimeFormatter
.ofPattern("yyyy-MM-dd")
.withZone(ZoneId.of("UTC"));
return LocalDate.parse(timeStr, formatter2).atStartOfDay().atZone(ZoneId.of("UTC")).toInstant();
}
}
cover
-
yyyy-MM-dd
-
yyyy-MM -dd HH
-
yyyy-MM-dd HH:mm
-
yyyy-MM-dd HH:mm:ss
-
yyyy-MM-dd HH: mm:ss SSSSSSSS
yyyy-MM-dd
yyyy-MM-dd HH
yyyy-MM-dd HH:mm
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd HH:mm:ss SSSSSSSS
这篇关于Java-多种方案的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文