杰瑞科技汇

Java日期如何精确转为时间?

Of course! The question "Java date to time" can mean a few different things. I'll cover the most common interpretations:

Java日期如何精确转为时间?-图1
(图片来源网络,侵删)
  1. Getting the Current Time (The most common request)
  2. Formatting a Date/Time Object into a String
  3. Parsing a String into a Date/Time Object
  4. Getting Specific Time Components (hour, minute, second)

Let's go through each one, starting with the modern, recommended approach using the java.time package (available since Java 8).


Getting the Current Time (Modern Approach - java.time)

The java.time package is the current standard for handling dates and times in Java. It's immutable, thread-safe, and much easier to use than the old java.util.Date.

The primary classes you'll use are:

  • LocalDateTime: Represents a date and time without a time zone (e.g., "2025-10-27T10:15:30").
  • ZonedDateTime: Represents a date and time with a time zone (e.g., "2025-10-27T10:15:30+02:00[Europe/Paris]").
  • Instant: Represents a specific moment on the timeline in UTC (useful for machine time).

Example: Get the current date and time

import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.Instant;
public class GetCurrentTime {
    public static void main(String[] args) {
        // 1. Get the current date and time in the system's default time zone
        LocalDateTime now = LocalDateTime.now();
        System.out.println("Local Date and Time: " + now);
        // Example Output: Local Date and Time: 2025-10-27T10:15:30.123456789
        // 2. Get the current date, time, and time zone information
        ZonedDateTime nowWithZone = ZonedDateTime.now();
        System.out.println("Zoned Date and Time: " + nowWithZone);
        // Example Output: Zoned Date and Time: 2025-10-27T10:15:30.123456789-04:00[America/New_York]
        // 3. Get the current moment in UTC (Coordinated Universal Time)
        Instant nowUtc = Instant.now();
        System.out.println("Current UTC Instant: " + nowUtc);
        // Example Output: Current UTC Instant: 2025-10-27T14:15:30.123456789Z
    }
}

Formatting a Date/Time Object into a String

You often need to display a date/time in a specific format (e.g., "MM/dd/yyyy" or "HH:mm:ss"). The DateTimeFormatter class is used for this.

Java日期如何精确转为时间?-图2
(图片来源网络,侵删)

Example: Formatting LocalDateTime

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatDateTime {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        // Define a custom format pattern
        // yyyy = year, MM = month, dd = day
        // HH = hour (24-hour), mm = minute, ss = second
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // Format the LocalDateTime object into a String
        String formattedDateTime = now.format(formatter);
        System.out.println("Original LocalDateTime: " + now);
        System.out.println("Formatted String:       " + formattedDateTime);
        // Example Output:
        // Original LocalDateTime: 2025-10-27T10:15:30.123456789
        // Formatted String:       2025-10-27 10:15:30
    }
}

Common Format Symbols:

  • yyyy: Year (e.g., 2025)
  • MM: Month in year (e.g., 10 for October)
  • dd: Day in month (e.g., 27)
  • HH: Hour in day (0-23)
  • hh: Hour in am/pm (1-12)
  • mm: Minute in hour
  • ss: Second in minute
  • a: AM/PM marker

Parsing a String into a Date/Time Object

This is the reverse of formatting. You have a string (e.g., from a user or a database) and you want to convert it into a java.time object.

Example: Parsing a String into LocalDateTime

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class ParseDateTime {
    public static void main(String[] args) {
        String dateTimeString = "2025-12-25 15:30:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            // Parse the string into a LocalDateTime object
            LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
            System.out.println("Parsed LocalDateTime: " + dateTime);
            // Example Output: Parsed LocalDateTime: 2025-12-25T15:30:00
        } catch (DateTimeParseException e) {
            System.err.println("Error: Unable to parse date/time string. " + e.getMessage());
        }
    }
}

Getting Specific Time Components (Hour, Minute, etc.)

Once you have a LocalDateTime object, you can easily extract parts of it.

Example: Extracting Hour, Minute, Second

import java.time.LocalDateTime;
public class GetTimeComponents {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        int nano = now.getNano();
        System.out.println("Current Hour:   " + hour);
        System.out.println("Current Minute: " + minute);
        System.out.println("Current Second: " + second);
        System.out.println("Current Nano:   " + nano);
    }
}

Legacy Approach: java.util.Date and SimpleDateFormat

Before Java 8, this was the standard way to handle dates and times. It's now considered legacy and you should avoid it in new code, but you might encounter it in older projects.

Important: java.util.Date is poorly designed. It represents both a date and time, but its methods for getting the year are 0-indexed (so 2025 is year + 1900) and its month is 1-indexed (so January is month - 1). This is a common source of bugs.

Example: Using java.util.Date

import java.util.Date;
import java.text.SimpleDateFormat;
public class LegacyDateExample {
    public static void main(String[] args) {
        // 1. Get the current date and time
        Date now = new Date();
        System.out.println("java.util.Date: " + now);
        // Example Output: java.util.Date: Wed Oct 27 10:15:30 EDT 2025
        // 2. Format the Date object into a String
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = formatter.format(now);
        System.out.println("Formatted String: " + formattedDate);
        // Example Output: Formatted String: 2025-10-27 10:15:30
        // 3. Parse a String into a Date object
        String dateString = "2025-12-25 15:30:00";
        try {
            Date parsedDate = formatter.parse(dateString);
            System.out.println("Parsed Date: " + parsedDate);
            // Example Output: Parsed Date: Mon Dec 25 15:30:00 EST 2025
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Summary: Which One to Use?

Scenario Recommended Modern Approach (java.time) Legacy Approach (java.util.Date)
New Applications Always use java.time. Avoid.
Getting Current Time LocalDateTime.now() or Instant.now() new Date()
Formatting/Parsing DateTimeFormatter SimpleDateFormat (not thread-safe)
Storing in Databases Use java.sql.Timestamp (wrapper for Instant) or java.sql.Date (wrapper for LocalDate) Use java.sql.Timestamp or java.sql.Date directly.
Interacting with Legacy Code Use Date.from(instant) and date.toInstant() for conversion. N/A

For any new Java development, stick with the java.time package. It is superior in almost every way.

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