简体   繁体   English

ThreeTen和解析瞬发

[英]ThreeTen and parsing an Instant

I'm using ThreeTen and attempted to format an Instant. 我正在使用ThreeTen并尝试格式化Instant。 Would be easier to just split it but I'm curious, should this work? 分开它会更容易,但我很好奇,这应该有效吗? From everything I've read Instant should be parse-able, and with all the components of the pattern: 从我读过的所有内容中,Instant应该是可解析的,并且具有模式的所有组件:

@Test
public void testInstants()  {
    Instant instant = Instant.now();
    String dbDatePattern = "YYYY-MM-dd HH:mm:ss.SSS";
    try {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dbDatePattern);
        String dbDate = formatter.format(instant);
    } catch (Exception ex) {
        int dosomething = 1;
    }
}

Error: org.threeten.bp.temporal.UnsupportedTemporalTypeException: Unsupported field: DayOfWeek 错误:org.threeten.bp.temporal.UnsupportedTemporalTypeException:不支持的字段:DayOfWeek

dd is day of month not DayofWeek. dd是DayofWeek的月份日期。 Probably getting tossed a red herring, but it seems odd. 可能会被扔红鲱鱼,但看起来很奇怪。

The pattern letter "Y" means week-based-year in ThreeTen-Backport and JSR-310 (it meant year-of-era in Joda-Time). 模式字母“Y”表示ThreeTen-Backport和JSR-310中的基于周的年份(它意味着Joda-Time的年代)。 In order to calculate the week-based-year, the day-of-week is needed, hence the error. 为了计算基于周的年份,需要星期几,因此错误。

Note that an Instant cannot supply fields for the formatter you are trying to create. 请注意, Instant无法为您尝试创建的格式化程序提供字段。 Only a ZonedDateTime , LocalDateTime or OffsetDateTime can. 只有ZonedDateTimeLocalDateTimeOffsetDateTime可以。 An Instant is a special case that must be formatted using DateTimeFormatter.ISO_INSTANT or similar. Instant是一种特殊情况,必须使用DateTimeFormatter.ISO_INSTANT或类似格式进行格式化。

To make explicit JodaStephen's answer: 明确JodaStephen的答案:

String dbDatePattern = "YYYY-MM-dd HH:mm:ss.SSS"; (uppercase YYYY) (大写YYYY)

should be 应该

String dbDatePattern = "yyyy-MM-dd HH:mm:ss.SSS"; (lowercase yyyy) (小写yyyy)

instead. 代替。

Also, instead of 而且,而不是

Instant instant = Instant.now();

do

LocalDateTime localDateTime = LocalDateTime.now();

...and then pass that to format() instead. ...然后将其传递给format()

Since both Instant and LocalDateTime implement TemporalAccessor , which is what DateTimeFormatter.format() accepts, the rest of your code should work as-is. 由于InstantLocalDateTime实现了TemporalAccessor ,这是DateTimeFormatter.format()接受的,因此其余代码应该按原样运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM