当前位置: 首页 > 知识库问答 >
问题:

当格式化Instant到String时,不支持

雍俊远
2023-03-14

我试图格式化一个即时到字符串使用新的Java8日期和时间API和以下模式:

Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);

使用上面的代码,我得到一个异常,它抱怨一个不支持的字段:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
    at java.time.Instant.getLong(Instant.java:608)
    at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
    ...

共有3个答案

金承嗣
2023-03-14
DateTimeFormatter.ISO_INSTANT.format(Instant.now())

这使您无需转换为UTC。然而,其他一些语言的时间框架可能不支持毫秒,所以您应该这样做

DateTimeFormatter.ISO_INSTANT.format(Instant.now().truncatedTo(ChronoUnit.SECONDS))
夏弘文
2023-03-14
public static void main(String[] args) {

    DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            .withZone(ZoneId.systemDefault());

    System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));

}
苗运珧
2023-03-14

要设置即时格式,需要时区。如果没有时区,格式化程序不知道如何将即时时间字段转换为人工日期时间字段,因此会引发异常。

时区可以直接添加到格式化程序使用with Zone()

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

如果您特别想要一个没有明确时区的ISO-8601格式(如OP所要求的),并且时区隐含UTC,您需要

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

现在,使用该格式化程序生成即时消息的字符串表示形式。

Instant instant = Instant.now();
String output = formatter.format( instant );

转储到控制台。

System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );

跑步的时候。

formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34
 类似资料:
  • 问题内容: 我正在尝试使用这种格式来格式化当前时间。 输出: 有什么建议? 问题答案: 用 由于Go使用以下常量来格式化日期,请参阅此处

  • 问题内容: 我的号码是654987。它是数据库中的ID。我想将其转换为字符串。常规的Double.ToString(value)使它成为科学形式6.54987E5。我不想要的东西。 我发现的其他格式化功能会检查当前的语言环境,并添加适当的千位分隔符等。由于它是一个ID,我完全不能接受任何格式。 怎么做? [编辑]要澄清:我正在一个特殊的数据库上工作,该数据库将所有数字列都视为双精度。 Double

  • 问题内容: 我正在尝试使用Jackson 将ISO8601格式的日期反序列化为Java8 。我向ObjectMapper注册了JavaTimeModule,并关闭了该设置。 但是,如果尝试反序列化,它将无法正常工作,因为JavaTimeModule似乎只会反序列化具有UTC时区偏移量的日期时间(例如)。然后,我尝试使用如下注释: 像这样: 但是,这些都不起作用,我得到一个例外: 这意味着将忽略ti

  • 我试图用一种特定的格式将“即时”格式化为“字符串”。基于这里的问题,我正在做这个- 有什么关于为什么会这样的建议吗? 谢谢

  • For %U, all days in a new year preceding the first Sunday are considered to be in week 0. For %W, all days in a new year preceding the first Monday are considered to be in week 0. In some implementati

  • 我想用haar cascade数数汽车。 我将图像正确地转换为灰度,并成功地在框架上画了一条线。问题是我得到了这个错误 错误:OpenCV(3.4.2)C:\build\3\u 4\u winpack-bindings-win32-vc14-static\OpenCV\modules\imgproc\src\contours。cpp:199:错误:(-210:不支持的格式或格式组合)[Start]