Joda-Time中的自由日期/时间解析 [英] Liberal date/time parsing in Joda-Time

查看:268
本文介绍了Joda-Time中的自由日期/时间解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个可以解析的DateTimeParser:

Is it possible to create a single DateTimeParser which would parse:

  • 有时间的日期
  • 没有时间的日期(假设时间是一天的开始)
  • 没有日期的时间(假设日期是今天)

还是我需要拥有三个单独的解析器,并尝试分别解析一个字符串?

or do I need to have three separate parsers, and try parsing strings with each one?

换句话说,是否可以在解析器中定义可选字段?

In other words, is it possible to define optional fields in a parser?

推荐答案

org.joda.time.format.ISODateTimeFormat具有基于DateTimeFomatterBuilder类的静态方法dateOptionalTimeParser(),该方法使用下面的代码,该类具有appendOptional方法-您可能可以使该方法适应您的要求...链接:

org.joda.time.format.ISODateTimeFormat has a static method dateOptionalTimeParser() that uses the code below, based on the DateTimeFomatterBuilder class, which has an appendOptional method - you would probably be able to adapt the method to your requirement... Link: http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormatterBuilder.html

public static DateTimeFormatter dateOptionalTimeParser() {
    if (dotp == null) {
        DateTimeParser timeOrOffset = new DateTimeFormatterBuilder()
            .appendLiteral('T')
            .appendOptional(timeElementParser().getParser())
            .appendOptional(offsetElement().getParser())
            .toParser();
        dotp = new DateTimeFormatterBuilder()
            .append(dateElementParser())
            .appendOptional(timeOrOffset)
            .toFormatter();
    }
    return dotp;
}

这篇关于Joda-Time中的自由日期/时间解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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