java日期 不同格式2 2,Java从几种日期格式中确定一种日期格式

We want to get a correct dateformat from LOG files generated by different systems with different language and log mechanism.

We thought this can be done be a SimpleDataFormat.parse and try-catch exception way. But the follow code shows a problem.

String tryparseString = "18-01-22 00:03:34:071";

try {

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println(sdf1.parse(tryparseString));

System.out.println(sdf1.format(sdf1.parse(tryparseString)));

System.out.println("Yeah! We found a CAN PARSE datefromat = " + sdf1.toPattern());

SimpleDateFormat sdf2 = new SimpleDateFormat("yy-MM-dd HH:mm:ss:SSS");

System.out.println(sdf2.parse(tryparseString));

System.out.println(sdf2.format(sdf2.parse(tryparseString)));

System.out.println("Yeah! We found a CAN PARSE datefromat = " + sdf2.toPattern());

} catch (ParseException e) {

e.printStackTrace();

}

This got a result as:

Sat Jan 22 00:03:34 CST 18

0018-01-22 00:03:34

Yeah! We found a CAN PARSE datefromat = yyyy-MM-dd HH:mm:ss

Mon Jan 22 00:03:34 CST 2018

18-01-22 00:03:34:000

Yeah! We found a CAN PARSE datefromat = yy-MM-dd HH:mm:ss:SSS

So, "18-01-22 00:03:34:071" can both be formatted with yyyy-MM-dd HH:mm:ss and yy-MM-dd HH:mm:ss:SSS.

The former one is far away correct.

So, is there a way to determine a correct dateformat from serveral dateformats?

解决方案

java.time to the rescue.

String[] formats = {

"yyyy-MM-dd HH:mm:ss",

"yy-MM-dd HH:mm:ss:SSS"

};

String tryparseString = "18-01-22 00:03:34:071";

for (String format : formats) {

try {

LocalDateTime.parse(tryparseString, DateTimeFormatter.ofPattern(format));

System.out.println("Yeah! We found a CAN PARSE date format = " + format);

} catch (DateTimeParseException dtpe) {

System.out.println(dtpe);

}

}

This prints:

java.time.format.DateTimeParseException: Text '18-01-22 00:03:34:071' could not be parsed at index 0

Yeah! We found a CAN PARSE datefromat = yy-MM-dd HH:mm:ss:SSS

In other words, the first format, yyyy-MM-dd HH:mm:ss, fails to parse your sample string, and the second succeeds as you wanted it to.

If you still experience a case where a DateTimeFormatter parses a string it shouldn’t, you may try DateTimeFormatter.ofPattern(format).withResolverStyle(ResolverStyle.STRICT). It may catch a few more non-matching strings. In this case you will need uuuu and uu instead of yyyy and yy in the format patterns, though.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值