杰瑞科技汇

Java日期如何转为整数?

Of course! Converting a Java Date object to an integer is a common task, but it's important to understand why you're doing it, as the "best" method depends on your goal.

Java日期如何转为整数?-图1
(图片来源网络,侵删)

Here are the most common scenarios and the best ways to handle them in modern Java (using java.time).

Scenario 1: Convert to a Unix Timestamp (Most Common)

This is the most frequent reason for the conversion. A Unix timestamp is the number of seconds (or milliseconds) that have elapsed since January 1, 1970 (the "Epoch"). It's a standard way to represent a point in time as a single number.

Method A: Using java.time (Recommended for Java 8+)

The modern java.time package is the standard way to handle dates and times. It's clearer, less error-prone, and immutable.

import java.time.Instant;
import java.util.Date;
public class DateToIntegerExample {
    public static void main(String[] args) {
        // 1. Get the current date and time
        Date now = new Date();
        // 2. Convert the legacy Date object to the modern Instant
        // Instant represents a point on the timeline in UTC.
        Instant instant = now.toInstant();
        // 3. Get the epoch seconds (as a long)
        long epochSeconds = instant.getEpochSecond();
        // 4. Get the epoch milliseconds (as a long)
        long epochMilliseconds = instant.toEpochMilli();
        // Since you asked for an integer, you can cast the long to an int.
        // WARNING: Be careful with overflow! The max value for a 32-bit int
        // is about 2.1 billion, which corresponds to a date in January 2038.
        // For most practical purposes, milliseconds will overflow sooner.
        // It's safer to use a long, but here is the cast as requested.
        int epochSecondsAsInt = (int) epochSeconds;
        int epochMillisecondsAsInt = (int) epochMilliseconds;
        System.out.println("Current Date: " + now);
        System.out.println("Epoch Seconds (long): " + epochSeconds);
        System.out.println("Epoch Seconds (int): " + epochSecondsAsInt);
        System.out.println("Epoch Milliseconds (long): " + epochMilliseconds);
        System.out.println("Epoch Milliseconds (int): " + epochMillisecondsAsInt);
    }
}

Key Points:

Java日期如何转为整数?-图2
(图片来源网络,侵删)
  • Use long instead of int: The range of a long is much larger, preventing overflow issues for decades to come. Only cast to int if you are certain your values will always fit and you have a specific API requirement.
  • Instant: This is the core class for representing a point in time, independent of time zones.

Method B: Using java.util.Date (Legacy)

If you're working with older code that can't be updated to java.time, you can call the built-in methods directly on the Date object.

import java.util.Date;
public class LegacyDateToIntegerExample {
    public static void main(String[] args) {
        Date now = new Date();
        // getTime() returns the number of milliseconds since the Epoch (as a long)
        long millisecondsSinceEpoch = now.getTime();
        // Convert to integer
        int millisecondsAsInt = (int) millisecondsSinceEpoch;
        System.out.println("Current Date: " + now);
        System.out.println("Milliseconds since Epoch (long): " + millisecondsSinceEpoch);
        System.out.println("Milliseconds since Epoch (int): " + millisecondsAsInt);
    }
}

Key Points:

  • Date.getTime() is the equivalent of Instant.toEpochMilli().
  • This method is simple but lacks the clarity and type safety of java.time.

Scenario 2: Convert to an Integer Representing YYYYMMDD

Sometimes, people want an integer that represents just the date part (year, month, day), for example, 20251027 for October 27, 2025. This is highly discouraged because it's not a standard format and can be ambiguous (e.g., is 101 January 1st or October 1st?).

However, if you must do it, java.time makes it safer.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DateToYYYYMMDD {
    public static void main(String[] args) {
        // Get today's date
        LocalDate today = LocalDate.now();
        // Define a formatter to get the year as 4 digits, month as 2, day as 2
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // Format the date into a String
        String dateString = today.format(formatter); // e.g., "20251027"
        // Convert the String to an Integer
        int dateAsInt = Integer.parseInt(dateString);
        System.out.println("LocalDate: " + today);
        System.out.println("Formatted String: " + dateString);
        System.out.println("As Integer: " + dateAsInt);
    }
}

Why this is a bad idea:

  • Sorting: Sorting these integers as numbers will not work correctly for the month and day parts (101 vs 111).
  • Ambiguity: As mentioned, it's hard to parse back without knowing the format.
  • Error-Prone: Easy to make mistakes with formatting.

Better Alternative: Just store the date as a LocalDate object. It's type-safe, unambiguous, and has built-in methods for comparison, arithmetic, etc.


Summary: Which Method Should You Use?

Your Goal Recommended Method Why?
Get a unique number for a point in time Instant.toEpochMilli() (as a long) Standard, unambiguous, universally understood (Unix timestamp). Use long to avoid overflow.
Get a unique number for a date (YYYYMMDD) Don't do this. Use LocalDate instead. It's not a standard, is ambiguous, and error-prone. Storing the date object is always better.
You are forced to use a 32-bit integer (int) (new Date().getTime() / 1000) This gets you seconds since the epoch. Be very aware of the Year 2038 problem where this will overflow.
You are working with legacy code Date.getTime() (as a long) It's the only way if you can't use java.time. Prefer long over int here as well.

Final Recommendation: For any new code, always prefer java.time. Use Instant and toEpochMilli() to get a long representing the timestamp. It's the most robust and standard approach.

分享:
扫描分享到社交APP
上一篇
下一篇