杰瑞科技汇

Java中如何获取与转换Unix时间戳?

Of course! Here is a comprehensive guide on how to work with Unix timestamps in Java, covering conversion, parsing, and best practices.

Java中如何获取与转换Unix时间戳?-图1
(图片来源网络,侵删)

What is a Unix Timestamp?

A Unix timestamp (also known as Unix time, POSIX time, or Epoch time) is a system for describing a point in time. It is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds.


Getting the Current Unix Timestamp

The most common task is to get the current timestamp. In Java 8 and later, the modern and recommended way is to use the java.time package.

Using java.time.Instant (Java 8+)

Instant is the class that represents a point on the timeline in UTC. It's the perfect choice for Unix timestamps.

import java.time.Instant;
public class CurrentTimestamp {
    public static void main(String[] args) {
        // Get the current moment in UTC
        Instant now = Instant.now();
        // Convert to seconds (the standard Unix timestamp)
        long currentTimestampInSeconds = now.getEpochSecond();
        // Convert to milliseconds (often used in Java and JavaScript)
        long currentTimestampInMilliseconds = now.toEpochMilli();
        System.out.println("Current Instant: " + now);
        System.out.println("Unix Timestamp (seconds): " + currentTimestampInSeconds);
        System.out.println("Unix Timestamp (milliseconds): " + currentTimestampInMilliseconds);
    }
}

Output:

Java中如何获取与转换Unix时间戳?-图2
(图片来源网络,侵删)
Current Instant: 2025-10-27T10:30:00.123456789Z
Unix Timestamp (seconds): 1698376200
Unix Timestamp (milliseconds): 1698376200123

Converting a Unix Timestamp to a Date/Time Object

You often need to convert a timestamp (a number) into a human-readable date and time.

Using java.time.Instant and java.time.ZonedDateTime (Java 8+)

This is the standard, modern approach.

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimestampToDateTime {
    public static void main(String[] args) {
        // Example timestamp in seconds
        long timestampInSeconds = 1698376200;
        // 1. Create an Instant from the timestamp
        Instant instant = Instant.ofEpochSecond(timestampInSeconds);
        // 2. Convert to a ZonedDateTime in a specific timezone
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("America/New_York"));
        // 3. Format the date and time
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
        String formattedDateTime = zonedDateTime.format(formatter);
        System.out.println("Timestamp: " + timestampInSeconds);
        System.out.println("UTC Instant: " + instant);
        System.out.println("New York Time: " + formattedDateTime);
        // Example with milliseconds
        long timestampInMilliseconds = 1698376200123L;
        Instant instantMs = Instant.ofEpochMilli(timestampInMilliseconds);
        ZonedDateTime zonedDateTimeMs = instantMs.atZone(ZoneId.of("Europe/London"));
        System.out.println("\nTimestamp (ms): " + timestampInMilliseconds);
        System.out.println("London Time: " + zonedDateTimeMs.format(formatter));
    }
}

Output:

Timestamp: 1698376200
UTC Instant: 2025-10-27T10:30:00Z
New York Time: 2025-10-27 06:30:00 EDT
Timestamp (ms): 1698376200123
London Time: 2025-10-27 11:30:01 GMT

Converting a Date/Time Object to a Unix Timestamp

This is the reverse operation: converting a date string or a java.time object into a timestamp.

Java中如何获取与转换Unix时间戳?-图3
(图片来源网络,侵删)

Using java.time.ZonedDateTime (Java 8+)

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeToTimestamp {
    public static void main(String[] args) {
        // Example date string
        String dateString = "2025-12-25T15:00:00";
        String timeZone = "Asia/Tokyo";
        // 1. Parse the string into a ZonedDateTime object
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateString + "[" + timeZone + "]");
        // 2. Convert the ZonedDateTime to an Instant (which is in UTC)
        Instant instant = zonedDateTime.toInstant();
        // 3. Get the epoch seconds
        long timestampInSeconds = instant.getEpochSecond();
        System.out.println("Original Date/Time: " + zonedDateTime);
        System.out.println("Corresponding Timestamp (seconds): " + timestampInSeconds);
    }
}

Output:

Original Date/Time: 2025-12-25T15:00:00+09:00[Asia/Tokyo]
Corresponding Timestamp (seconds): 1703506800

Legacy Methods (Pre-Java 8)

If you are working on an older codebase or using an older Java version, you might encounter the java.util.Date and java.util.Calendar classes. It is highly recommended to use the modern java.time API for new code.

Using java.util.Date

import java.util.Date;
public class LegacyTimestamp {
    public static void main(String[] args) {
        // Get current time as a Date object
        Date now = new Date();
        // getTime() returns milliseconds since the epoch
        long timestampInMilliseconds = now.getTime();
        // To get seconds, divide by 1000
        long timestampInSeconds = timestampInMilliseconds / 1000;
        System.out.println("Current Date: " + now);
        System.out.println("Timestamp (milliseconds): " + timestampInMilliseconds);
        System.out.println("Timestamp (seconds): " + timestampInSeconds);
        // Creating a Date from a timestamp
        long specificTimestamp = 1698376200L; // seconds
        Date specificDate = new Date(specificTimestamp * 1000L);
        System.out.println("\nDate from timestamp: " + specificDate);
    }
}

Summary: Key Classes and Methods

Task Modern java.time API (Java 8+) Legacy java.util API (Pre-Java 8)
Get current timestamp (seconds) Instant.now().getEpochSecond() new Date().getTime() / 1000
Get current timestamp (milliseconds) Instant.now().toEpochMilli() new Date().getTime()
Convert timestamp (s) to Instant Instant.ofEpochSecond(seconds) new Date(seconds * 1000L)
Convert timestamp (ms) to Instant Instant.ofEpochMilli(milliseconds) new Date(milliseconds)
Format Instant to a string instant.atZone(ZoneId.of("...")).format(formatter) new SimpleDateFormat("...").format(date)
Parse string to Instant ZonedDateTime.parse("...").toInstant() new SimpleDateFormat("...").parse("...").toInstant() (more complex)

Best Practices

  1. Use java.time for all new code. It's immutable, thread-safe, and far more intuitive than the legacy java.util.Date/Calendar API.
  2. Be aware of seconds vs. milliseconds.
    • The classic Unix standard is seconds.
    • Many systems, especially JavaScript (Date.now()) and Java's own System.currentTimeMillis(), use milliseconds.
    • Always double-check which unit a timestamp is in to avoid off-by-1000 errors.
  3. Handle Time Zones explicitly. When displaying a timestamp to a user, always convert it to their local time zone using ZoneId. Storing and transmitting timestamps in UTC (Instant) is the best practice.
分享:
扫描分享到社交APP
上一篇
下一篇