【问题标题】:JodaTime : How to get ISO formatted time from DateTime object?JodaTime:如何从 DateTime 对象获取 ISO 格式的时间?
【发布时间】:2023-03-16 21:54:01
【问题描述】:

我正在使用 Joda 获取 DTO:

dateTimeObj = new DateTime();

我想将此 DTO 转换为 ISO 格式的格式化字符串:

2016-03-06T11:30:00-05:00

我尝试过使用:

dateTimeObj = new DateTime().toDateTimeISO();

但没有运气。

请问我该如何以正确的方式做到这一点?

【问题讨论】:

    标签: android datetime jodatime


    【解决方案1】:

    toDateTimeISO() 已弃用,请使用 toDateTime() http://joda-time.sourceforge.net/apidocs/org/joda/time/Instant.html

    还有:

    DateTime dt = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM, yyyy");
    String str = fmt.print(dt);
    

    在此处查看模式语法: http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html

    【讨论】:

    • 嗯,我看不出“MMMM,yyyy”如何匹配所需的输出“2016-03-06T11:30:00-05:00”?
    • @MenoHochschild 它没有。我提供了简短的示例和详细信息的链接。适当的模式在下面的评论中给出。
    【解决方案2】:

    您可以使用IsoDateTimeFormat.dateTimeNoMillis() 获取没有毫秒部分的格式:

     DateTime dt = new DateTime();
     DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
     String str = fmt.print(dt);
    

    【讨论】:

      【解决方案3】:

      您可以像这样调用format 方法:

      .format(DateTimeFormatter.ISO_INSTANT));
      

      【讨论】:

        【解决方案4】:

        首先,您需要使用 LocalDateTime 而不是 DateTime 才能访问您格式中的时区。

        使用DateTimeFormatter,其格式与图表中定义的here 相同。

        你想要的格式是“YYYY-MM-DDTHH:mm:ss-ZZZZ”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-21
          • 2010-09-12
          • 2016-07-18
          相关资源
          最近更新 更多