首页  >  文章  >  Java  >  如何将 Unix Epoch 时间转换为 Java Date 对象?

如何将 Unix Epoch 时间转换为 Java Date 对象?

Barbara Streisand
Barbara Streisand原创
2024-11-15 13:51:02748浏览

How do I convert Unix Epoch time to a Java Date object?

Converting Unix Epoch Time to Java Date Object

Unix Epoch time, often referred to as Unix timestamp, represents the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. In Java, we can convert Unix Epoch time to a Date object, which represents a specific moment in time.

To perform this conversion, you can utilize the Date class in Java's java.util package. The Date constructor accepts a long value representing the number of milliseconds since the Epoch.

Example:

Consider the following code snippet:

String date = "1081157732";
Date expiry = new Date(Long.parseLong(date) * 1000);

In this example, we start with a String representing the Unix Epoch time. We then call Long.parseLong() to parse the String and convert it to a long. Since Unix timestamps are typically expressed in seconds, we multiply the resulting long value by 1000 to convert it to milliseconds, the unit used by Java's Date constructor.

By creating a new Date object using the Date(long) constructor and passing the converted milliseconds, we effectively create a Java Date object corresponding to the specified Unix Epoch time. This Date object represents the specific moment in time associated with that timestamp.

以上是如何将 Unix Epoch 时间转换为 Java Date 对象?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn