Home > Java > javaTutorial > How do I convert a UNIX Epoch Time string into a Java Date object?

How do I convert a UNIX Epoch Time string into a Java Date object?

Susan Sarandon
Release: 2024-11-21 03:04:16
Original
790 people have browsed it

How do I convert a UNIX Epoch Time string into a Java Date object?

Converting UNIX Epoch Time to Java Date Object

In Java, converting a UNIX Epoch time (represented as a string) into a Date object requires a two-step process.

Step 1: Parsing the Epoch Time

The UNIX Epoch time is typically expressed as a string representing the number of seconds since the epoch (January 1, 1970). To parse this string as a long integer, use the Long.parseLong() method, as seen in the following code:

String date = "1081157732";
long epochTime = Long.parseLong(date);
Copy after login

Step 2: Converting Seconds to Milliseconds

Java's Date constructor expects the epoch time to be specified in milliseconds. Therefore, we need to convert the parsed seconds into milliseconds. For this, we can multiply the epochTime by 1000:

long millisecondEpochTime = epochTime * 1000;
Copy after login

Creating the Date Object

Finally, we can create a Date object using the converted millisecondEpochTime:

Date expiry = new Date(millisecondEpochTime);
Copy after login

And that's how you convert a UNIX Epoch time string into a Java Date object. Enjoy coding!

The above is the detailed content of How do I convert a UNIX Epoch Time string into a Java Date object?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template