joda time isodatetimeformat.datetime()行为异常

ig9co6j1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(456)

datetime()应该是宽松和灵活的。e、 g.毫秒是可选的,日期是可选的,时区是可选的,时区可以是可选的 Z 或者 +/- HH[:MM] 但事实并非如此。我错过了什么?
使用版本 joda-time:2.9.9 (也试过了) 2.10.8 (结果相同)

import org.joda.time.format.ISODateTimeFormat;
import java.util.Arrays;

public static void main(String[] args) {
    Arrays.asList("2020-11-22T01:59:59.001+00:00", "2020-11-22T01:59:59.001Z", "2020-11-22T01:59:59+00:00",
        "2020-11-22T01:59:59Z", "01:59:59").forEach(s -> {
        try {
            System.out.println(String.format("%-30s -- %s", s, ISODateTimeFormat.dateTime().parseDateTime(s)));
        } catch (Exception e) {
            System.out.println(String.format("%-30s -- %s", s, e.getMessage()));
        }
    });
}

输出:

2020-11-22T01:59:59.001+00:00  -- 2020-11-22T01:59:59.001Z
2020-11-22T01:59:59.001Z       -- 2020-11-22T01:59:59.001Z
2020-11-22T01:59:59+00:00      -- Invalid format: "2020-11-22T01:59:59+00:00" is malformed at "+00:00"
2020-11-22T01:59:59Z           -- Invalid format: "2020-11-22T01:59:59Z" is malformed at "Z"
01:59:59.000                   -- Invalid format: "01:59:59.000" is malformed at ":59:59.000"

javadoc公司:

public static DateTimeFormatter dateTimeParser()

Returns a generic ISO datetime parser which parses either a date or a time or both.

The returned formatter can only be used for parsing, printing is unsupported.

The parser is strict by default, thus time string 24:00 cannot be parsed.

It accepts formats described by the following syntax:

 datetime          = time | date-opt-time
 time              = 'T' time-element [offset]
 date-opt-time     = date-element ['T' [time-element] [offset]]
 date-element      = std-date-element | ord-date-element | week-date-element
 std-date-element  = yyyy ['-' MM ['-' dd]]
 ord-date-element  = yyyy ['-' DDD]
 week-date-element = xxxx '-W' ww ['-' e]
 time-element      = HH [minute-element] | [fraction]
 minute-element    = ':' mm [second-element] | [fraction]
 second-element    = ':' ss [fraction]
 fraction          = ('.' | ',') digit+
 offset            = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]])
mccptt67

mccptt671#

java.time文件

正如abra在一篇评论中所建议的,您可能希望遵循官方的joda时间建议,并继续使用java.time,即现代的java日期和时间api。
下面的内容并不能提供joda时间解析器的全部灵活性,但它确实可以解析您的五个示例字符串。你也许可以进一步调整它以适应你可能有的任何进一步的需要。

ZoneOffset defaultOffset = ZoneOffset.UTC; // Configurable
    LocalDate defaultDate = LocalDate.now(ZoneId.systemDefault());

    DateTimeFormatter flexibleFormatter = new DateTimeFormatterBuilder()
            .optionalStart()
            .append(DateTimeFormatter.ISO_LOCAL_DATE)
            .appendLiteral('T')
            .optionalEnd()
            .parseDefaulting(ChronoField.YEAR, defaultDate.getYear())
            .parseDefaulting(ChronoField.MONTH_OF_YEAR, defaultDate.getMonthValue())
            .parseDefaulting(ChronoField.DAY_OF_MONTH, defaultDate.getDayOfMonth())
            .append(DateTimeFormatter.ISO_LOCAL_TIME)
            .optionalStart()
            .appendOffsetId()
            .optionalEnd()
            .parseDefaulting(ChronoField.OFFSET_SECONDS, defaultOffset.getTotalSeconds())
            .toFormatter();

    Arrays.asList("2020-11-22T01:59:59.001+00:00", "2020-11-22T01:59:59.001Z", "2020-11-22T01:59:59+00:00",
            "2020-11-22T01:59:59Z", "01:59:59").forEach(s -> {
            try {
                System.out.println(String.format("%-30s -- %s", s, OffsetDateTime.parse(s, flexibleFormatter)));
            } catch (DateTimeParseException dtpe) {
                System.out.println(String.format("%-30s -- %s", s, dtpe.getMessage()));
            }
        });

我刚才在欧洲/哥本哈根时区跑步时的输出:

2020-11-22T01:59:59.001+00:00  -- 2020-11-22T01:59:59.001Z
2020-11-22T01:59:59.001Z       -- 2020-11-22T01:59:59.001Z
2020-11-22T01:59:59+00:00      -- 2020-11-22T01:59:59Z
2020-11-22T01:59:59Z           -- 2020-11-22T01:59:59Z
01:59:59                       -- 2020-11-19T01:59:59Z

从joda time主页:
请注意,joda time被认为是一个基本上“已完成”的项目。没有重大的增强计划。如果使用java se 8,请迁移到 java.time (jsr-310)。

你的代码哪里出错了?

詹斯格拉姆在评论中说:
你正在链接到的文档 dateTimeParser 但是调用 dateTime() ###链接
oracle教程:date time解释如何使用java.time。
乔达时间-回家

相关问题