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

}

The code works great as long as the String s has the format "2019-04-23 06:57:00.0";

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 ].

For example

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值