Explain Codes LogoExplain Codes Logo

Java: Date from unix timestamp

java
date-time
unix-timestamp
time-zones
Anton ShumikhinbyAnton Shumikhin·Aug 11, 2024
TLDR

A Unix timestamp in Java can be converted to a Date object by using new Date(unixTimestamp * 1000L) to convert seconds to milliseconds.

Date date = new Date(1633072800L * 1000L);

Learn to Time Travel: A Journey with java.util.Date and java.time

Java provides two significant ways to play around with dates and times: the good old java.util.Date class and the shiny new java.time package that came swinging with Java 8.

A Date with java.util.Date

Believe me or not, this old warrior java.util.Date is still kicking, especially when APIs demand its presence. It symbolizes a specific moment in time, millisecond accurate:

long unixTimestampInSeconds = 1633072800L; // Along came a Unix timestamp Date legacyDate = new Date(unixTimestampInSeconds * 1000L);

However, if the milliseconds value is already in your hands, why bother to convert?

long unixTimestampInMilliseconds = 1633072800000L; Date legacyDateFromMillis = new Date(unixTimestampInMilliseconds); // Direct, neat, and clean!

When working with Date, remember to pack time zones and formatting in your toolkit. Bring SimpleDateFormat along to add a touch of elegance to your Date object:

SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); String formattedDate = sdf.format(legacyDate); // Voila! A Date object, but make it fashion!

Living on the Edge with java.time

With the java.time API, also known as JSR-310, Java has truly stepped into the future. If you're twiddling with Java 8 or newer, favor this API over java.util.Date for superior capabilities and clarity:

Instant instant = Instant.ofEpochSecond(unixTimestampInSeconds); Date modernDate = Date.from(instant); // Time travel, the modern way!

For operations fully aware of time zones, ZonedDateTime is your ultimate companion:

ZoneId zoneId = ZoneId.of("America/New_York"); ZonedDateTime zonedDateTime = instant.atZone(zoneId);

And, last but not least, you can swing Instant directly to several types such as LocalDateTime, making it an absolute charm for all applications:

LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

Caveat Emptor: Mastering Tricky Scenarios and Compatibility

Wading through the oceans of timestamps and dates demands caution and foresight, particularly for special circumstances and cross compatibility.

When UNIX Meets String

There might be occasions when UNIX timestamps pose as string literals. Exercise caution and parse them to a numeric type before conversion:

String unixTimestampString = "1633072800"; long unixTimestamp = Long.parseLong(unixTimestampString); // Dressing up the wolf in sheep's clothing Date parsedDate = new Date(unixTimestamp * 1000L); // And, voila, ready for the ball!

Punk'd by Time Zones

Adept handling of time zones ensures accurate time across various regions, no nasty surprises:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); calendar.setTimeInMillis(unixTimestamp * 1000L); Date utcDate = calendar.getTime(); // Not punk'd by time zones anymore!

Travelling from the Past to Present

A smooth ride between java.util.Date and the java.time types helps when interacting with legacy and modern code:

// Converting from java.time.Instant to java.util.Date Instant instant = Instant.ofEpochSecond(unixTimestamp); Date convertedDate = Date.from(instant); // Making the jump to hyperspace! // Converting from java.util.Date to java.time.Instant Instant convertedInstant = convertedDate.toInstant(); // Re-entering the atmosphere

Pushing the Envelope with ThreeTen-Extra

For those who refuse to settle and demand more from date-time manipulations, the ThreeTen-Extra library complements java.time by providing some extra kicks:

// Complex calculations? Challenge accepted! Period tenDays = Period.ofDays(10);

As you dive deeper down the rabbit hole of date-time manipulation, remember to make good use of the rich repertoire of various libraries tailored to your exact needs.