首页 > 解决方案 > 现在以 16 位十六进制(16 个字符)获取时间和日期

问题描述

我目前正在使用

Calendar.getInstance().getTimeInMillis()/1000

以秒为单位获得日历中今天时间的结果。我需要将结果输出成这样的:

0000000ED76420A5

大端或小端无关紧要,但我的知识不足以转换它,我的朋友告诉我这与纪元时间有关,但我不确定为什么我没有得到正确的日期我转换的时间。

我使用的偏移量为:62168515200,但我也不明白这些是什么意思。

我将不胜感激任何帮助或资源..谢谢。

编辑:我正在在线使用纪元时间转换器(截至目前为 1574669899),但是有了这个数字,我怎样才能在 Java 中获得日期时间?如果我能够在 Java 中获得正确的日期时间,我也许可以进行转换,对吧?

标签: javadatetimeepoch

解决方案


如果您有 Java 8,则使用java.time和一些static方法Long来获得纪元毫秒的瞬间,将其转换为十六进制表示并以相反的方式执行。最后,以下示例显示了如何创建日期时间并打印它:

public static void main(String[] args) {
    // take the instant in epoch milliseconds
    long millis = Instant.now().toEpochMilli();
    // print them once
    System.out.println("millis:\t\t\t" + millis);
    // convert them to a hexadecimal representation
    String hexMillis = Long.toHexString(millis);
    // print them
    System.out.println("Hex-Millis:\t\t" + hexMillis);
    // convert the millis back, THIS NEEDS A LEADING 0x
    long convertedMillis = Long.decode("0x" + hexMillis);
    // print the value and see that it's the same as above
    System.out.println("Converted millis:\t" + convertedMillis);
    // create an Instant from the converted millis
    Instant instant = Instant.ofEpochMilli(convertedMillis);
    // create a LocalDateTime from the Instant using the system default time zone
    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    // print the date-time formatted
    System.out.println("LocalDateTime:\t\t" 
            + localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
}

在我的系统上,这输出

Hex-Millis:         16ea1bbd03c
Converted millis:   1574671470652
LocalDateTime:      2019-11-25T09:44:30.652

推荐阅读