代码之家  ›  专栏  ›  技术社区  ›  amallard

为什么Java 8 Instant.now()在本地服务器上显示错误的UTC?

  •  0
  • amallard  · 技术社区  · 6 年前

    爪哇8 Instant.now() CompileJava.net

    Timestamp createdDateUtc = Timestamp.from(Instant.now());
    System.out.println(createdDateUtc);
    
    LocalDateTime databaseUtcLocal = createdDateUtc.toLocalDateTime();
    ZonedDateTime databaseUtcZoned = databaseUtcLocal.atZone(ZoneId.of("UTC"));
    ZonedDateTime userTimezoneTime = databaseUtcZoned.withZoneSameInstant(ZoneId.of("Asia/Qatar")); 
    System.out.println(userTimezoneTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a")));
    

    注:目前是2018年1月12日UTC上午11:16。

    在联机编译器上运行此代码时,我会得到以下输出:

    2018-12-01 11:17:43.637
    12/01/2018 02:17:43 PM
    

    2018-12-01 03:18:07.464
    12/01/2018 06:18:07 AM
    

    这里会出什么问题?我的服务器UTC时钟是否不正确?我的本地服务器的物理位置在加利福尼亚州。虽然这不重要,但当我试图使用 立即

    非常感谢任何帮助!

    更新

    正如公认的答案所指出的那样,这个问题是我的问题 Timestamp.from() 方法:

    System.out.println(Instant.now());
    System.out.println(Timestamp.from(Instant.now()));
    

    输出:

    2018-12-01T11:48:33.153Z
    2018-12-01 03:48:33.171
    

    here . 而不是 Timestamp.from(Instant.now())

    Timestamp.valueOf(ZonedDateTime.of(LocalDateTime.now(), ZoneId.systemDefault()).withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime())
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   codeformars    6 年前

    我认为这是一个问题 Timestamp.toString()

    public String toString () {
    
        int year = super.getYear() + 1900;
        int month = super.getMonth() + 1;
        int day = super.getDate();
        int hour = super.getHours();
        int minute = super.getMinutes();
        int second = super.getSeconds();
        // other code
    }
    

    方法 getHours() , getMinutes() 还有一些是从中国来的 Date 类,并根据文档按本地时区进行解释 Date.getHours()