【问题标题】:Can I get value of Curren time from miliseconds value [duplicate]我可以从毫秒值中获取当前时间的值吗[重复]
【发布时间】:2021-01-18 02:48:55
【问题描述】:

我有一个以毫秒为单位的值 1601626934449

通过https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()生成

但我能否以某种方式获得人类可读格式的时间,或者简而言之,我需要能够知道以毫秒为单位的值 1601626934449 是多少?

【问题讨论】:

标签: java random datetime-format epoch milliseconds


【解决方案1】:

在 Java 8 或更高版本上使用 java.time。使用它,很容易达到您的目标。
您基本上从纪元毫秒(代表一个时刻)创建一个Instant,通过应用ZoneId(我的系统在以下示例中的默认设置)使其成为ZonedDateTime,然后格式化输出String通过内置的DateTimeFormatter 或通过创建具有所需模式的自定义模式,使其根据需要变得易于阅读。

这是一个例子:

public static void main(String[] args) {
    // your example millis
    long currentMillis = 1601626934449L;
    // create an instant from those millis
    Instant instant = Instant.ofEpochMilli(currentMillis);
    // use that instant and a time zone in order to get a suitable datetime object
    ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
    // then print the (implicitly called) toString() method of it
    System.out.println(currentMillis + " is " + zdt);
    // or create a different human-readable formatting by means of a custom formatter
    System.out.println(
        zdt.format(
            DateTimeFormatter.ofPattern(
                "EEEE, dd. 'of' MMMM uuuu 'at' HH:mm:ss 'o''clock in' VV 'with an offset of' xxx 'hours'",
                Locale.ENGLISH
            )
        )
    );
}

哪个输出(在我的系统上)

1601626934449 is 2020-10-02T10:22:14.449+02:00[Europe/Berlin]
Friday, 02. of October 2020 at 10:22:14 o'clock in Europe/Berlin with an offset of +02:00 hours

【讨论】:

  • 这个问题太常见了,我投票决定删除它,甚至没有看这个不错的答案。在投票删除后,我转向了这个答案,但已经很晚了,因为 SO 没有提供撤回删除投票的选项。尽管我的许多高质量答案都被浪费了,因为问题被删除了(在关闭后),而且我每次都感到非常难过,但我从未感到沮丧,因为无法撤回删除投票,所以我现在感到沮丧.我希望没有其他人投票删除这个问题!
  • @ArvindKumarAvinash 我认为这是 stackoverflow 游戏的一部分。所以没关系...有趣的是缺少撤回删除投票的可能性,不知道不能。感谢您的提及,在我投票删除问题之前,我会牢记这一点。
【解决方案2】:

您可以将毫秒转换为LocalDateTime 以存储时间

long millis = System.currentTimeMillis();
LocalDateTime datetime = Instant.ofEpochMilli(millis)
                                .atZone(ZoneId.systemDefault()).toLocalDateTime();

然后您可以使用toString() 打印您的数据或使用DateTimeFormatter 打印您想要的格式。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
System.out.println(datetime.format(formatter));

输出:2020-10-02 18:39:54.609

【讨论】:

    【解决方案3】:

    您可以创建一个 Date 对象并使用它来获取您需要的所有信息:

    https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date(long)

    【讨论】:

    • 我建议你不要。 Date 类设计不佳且早已过时。与其他两个答案一样,我们更喜欢使用现代 Java 日期和时间 API java.time。
    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2011-10-25
    • 2017-02-20
    • 1970-01-01
    • 2018-05-22
    • 2011-08-25
    • 1970-01-01
    相关资源
    最近更新 更多