【问题标题】:Joda DateTime toDate returns not as per Created DateTime [duplicate]Joda DateTime toDate 不按照 Created DateTime 返回 [重复]
【发布时间】:2019-10-04 10:38:49
【问题描述】:

您好,我注意到使用 Zone 创建的 Joda DateTime 根据当前系统日期返回 toDate。我期待 toDate 根据 Created DateTime 返回。根据 Joda API,它说 toDate 应该返回使用此日期时间初始化的日期。我在我的 Maven 中使用 Joda 2.9.4。来自大师的任何想法都在 SO

public class TestJodaError {

public static void main(String[] args) {
    DateTime ldt = new DateTime();
    System.out.println("Local dt: " + ldt + " toDate: " + ldt.toDate());

    String tzId = "Asia/Singapore";
    ZoneId zoneId = ZoneId.of(tzId);
    ZonedDateTime zdt = ZonedDateTime.now(zoneId);

    DateTimeZone dtZone = DateTimeZone.forID(zdt.getZone().getId());
    DateTime rdt = new DateTime(dtZone);
    System.out.println("Remote dt: " + rdt + " toDate: " + rdt.toDate());
}}

结果是

Local dt: 2019-05-17T11:33:30.333+05:30 toDate: Fri May 17 11:33:30 IST 2019
Remot dt: 2019-05-17T14:03:30.738+08:00 toDate: Fri May 17 11:33:30 IST 2019

预期结果

Remot dt: 2019-05-17T14:03:30.738+08:00 toDate: Fri May 17 14:03:30 SGT 2019

【问题讨论】:

  • toDate 是你的自定义函数吗?我在 Joda 中找不到它DateTime
  • 无需Zoda时间,使用Java 8即可实现。
  • @BilboBaggins 也许实际上是LocalDateTime
  • @AndyTurner 不确定,我一直在使用 Java 8、java.time 而不是 Joda time。只是想解决这个问题。 :)
  • toDate 方法来自 Joda DateTime

标签: java datetime timezone jodatime


【解决方案1】:

正如 Andy 提到的,Date 没有任何特定的时区信息。如果你想在没有 Joda 时间的情况下使用并想利用 Java 8,我在下面提供了代码 sn-p。

LocalDateTime ldt = LocalDateTime.of(2019, Month.MAY, 17, 11, 30);
ZonedDateTime klDateTime = ldt.atZone(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter indianFormat = DateTimeFormatter.ofPattern("dd MMM yyyy");

String output = klDateTime.format(indianFormat);

【讨论】:

    【解决方案2】:

    打印java.util.Date 将始终使用JVM 的默认时区,因为Date 实际上不包含任何时区信息。

    因此,如果ldt.toDate() 也打印在 IST 中,则打印 rdt.toDate() 的结果将在 IST 中打印。

    【讨论】:

    • 谢谢安迪,这说明了为什么...假设来自 Joda DateTime 的 toDate 将相应地遵循。
    猜你喜欢
    • 2015-11-24
    • 2016-03-17
    • 2011-06-13
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多