java - Joda DateTime toDate 返回的结果与 Created DateTime 不同

标签 java datetime timezone jodatime

您好,我注意到使用 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

最佳答案

正如 Andy 提到的,Date 不会有任何特定的时区信息。如果您想在没有 Joda 时间的情况下使用并希望利用 Java 8,我在下面提供了代码片段。

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);

关于java - Joda DateTime toDate 返回的结果与 Created DateTime 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56180612/

相关文章:

java - 仅在外大括号中用逗号分割字符串的算法

python - 带有来自日期时间向量的时间箱的直方图

python - 将字典键值从 UNIX 时间转换为人类可读时间

php - MySQL 中的时区设置 - 使用 NOW()?

java - Groovy 控制台不输出旧值

java - DSpace:Java 邮件无法在公司网络中运行

java - Spring WebFlux : Serve files from controller

c# - DateTime 自定义格式不符合预期

Java 获取特定时间的所有时区

javascript - FullCalendar:默认时区,与客户的位置无关