使用 Joda Date &用于解析多种格式的时间 API [英] Using Joda Date & Time API to parse multiple formats

查看:38
本文介绍了使用 Joda Date &用于解析多种格式的时间 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Joda 解析包含日期/时间的第三方日志文件.日期/时间采用两种不同格式之一,具体取决于我正在解析的日志文件的年龄.

I'm parsing third party log files containing date/time using Joda. The date/time is in one of two different formats, depending on the age of the log files I'm parsing.

目前我有这样的代码:

try {
    return DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").parseDateTime(datePart);
} catch (IllegalArgumentException e) {
    return DateTimeFormat.forPattern("E, MMM dd, yyyy HH:mm").parseDateTime(datePart);
}

这有效,但违反了有效 Java 2nd Edition 中 Joshua Bloch 的建议(条款 57:仅在特殊情况下使用异常).这也使得很难确定是否由于日志文件中的日期/时间错误而导致 IllegalArgumentException 发生.

This works but contravenes Joshua Bloch's advice from Effective Java 2nd Edition (Item 57: Use exceptions only for exceptional conditions). It also makes it hard to determine if an IllegalArgumentException occurs due to a screwed up date/time in a log file.

你能提出一种不会滥用异常的更好的方法吗?

Can you suggest a nicer approach that doesn't misuse exceptions?

推荐答案

您可以使用 DateTimeFormatterBuilder.append 方法:

DateTimeParser[] parsers = { 
        DateTimeFormat.forPattern( "yyyy-MM-dd HH" ).getParser(),
        DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append( null, parsers ).toFormatter();

DateTime date1 = formatter.parseDateTime( "2010-01-01" );
DateTime date2 = formatter.parseDateTime( "2010-01-01 01" );

这篇关于使用 Joda Date &用于解析多种格式的时间 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆