杰瑞科技汇

Java中yyyy-MM-dd格式如何正确使用?

Of course! In Java, handling dates in the yyyy-MM-dd format is a very common task. The modern and recommended way to do this is using the java.time package, introduced in Java 8.

Java中yyyy-MM-dd格式如何正确使用?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the most common scenarios.

Getting Today's Date in yyyy-MM-dd Format

This is the most frequent use case. You want to get the current date and represent it as a String in the yyyy-MM-dd format.

Key Classes:

  • LocalDate: Represents a date without time or a time zone (e.g., 2025-10-27).
  • DateTimeFormatter: A formatter for printing and parsing date-time objects.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class GetCurrentDate {
    public static void main(String[] args) {
        // 1. Get the current date
        LocalDate today = LocalDate.now();
        // 2. Define the desired format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 3. Format the date into a String
        String formattedDate = today.format(formatter);
        System.out.println("Today's date is: " + formattedDate);
    }
}

Output:

Java中yyyy-MM-dd格式如何正确使用?-图2
(图片来源网络,侵删)
Today's date is: 2025-10-27

(The output will be the actual current date when you run the code).


Parsing a String (yyyy-MM-dd) into a LocalDate Object

Sometimes you have a date as a string (e.g., from a user or a file) and you need to convert it into a LocalDate object to perform calculations or validations.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class ParseDateString {
    public static void main(String[] args) {
        String dateString = "2025-12-25";
        // Define the format of the input string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        try {
            // Parse the string into a LocalDate object
            LocalDate date = LocalDate.parse(dateString, formatter);
            System.out.println("Successfully parsed date: " + date);
            System.out.println("Year: " + date.getYear());
            System.out.println("Month: " + date.getMonth());
            System.out.println("Day: " + date.getDayOfMonth());
        } catch (DateTimeParseException e) {
            System.err.println("Error: Invalid date format. Please use yyyy-MM-dd.");
        }
    }
}

Output:

Successfully parsed date: 2025-12-25
Year: 2025
Month: DECEMBER
Day: 25

Formatting a LocalDate Object into a String (yyyy-MM-dd)

This is the reverse of parsing. You have a LocalDate object and want to display it as a String.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class FormatDateObject {
    public static void main(String[] args) {
        // Create a specific LocalDate object
        LocalDate date = LocalDate.of(2025, 8, 15);
        // Define the desired format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // Format the date object into a string
        String formattedString = date.format(formatter);
        System.out.println("The formatted date string is: " + formattedString);
    }
}

Output:

The formatted date string is: 2025-08-15

Handling Dates with Different Separators (e.g., yyyy/MM/dd)

The DateTimeFormatter is very flexible. If your input string uses slashes () instead of hyphens (), you just need to change the pattern in the formatter.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class DifferentSeparator {
    public static void main(String[] args) {
        String dateStringWithSlashes = "2025/01/20";
        // The pattern must match the input string
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        LocalDate date = LocalDate.parse(dateStringWithSlashes, formatter);
        // You can then format it back to a different style
        DateTimeFormatter hyphenFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedWithHyphens = date.format(hyphenFormatter);
        System.out.println("Parsed date: " + date);
        System.out.println("Formatted with hyphens: " + formattedWithHyphens);
    }
}

Output:

Parsed date: 2025-01-20
Formatted with hyphens: 2025-01-20

Important: Legacy java.util.Date and SimpleDateFormat

Before Java 8, the java.util.Date and SimpleDateFormat classes were used. It is highly recommended to avoid them in new code because they are mutable, not thread-safe, and have design flaws.

However, you might encounter them in older systems. Here's how you would do it with the legacy API for comparison.

import java.text.SimpleDateFormat;
import java.util.Date;
public class LegacyDateFormat {
    public static void main(String[] args) {
        // 1. Get the current date
        Date today = new Date();
        // 2. Create a SimpleDateFormat (NOT thread-safe!)
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        // 3. Format the date
        String formattedDate = formatter.format(today);
        System.out.println("Legacy format: " + formattedDate);
    }
}

Summary: Best Practices

Task Modern Java 8+ (java.time) Legacy (java.util)
Get current date LocalDate.now() new Date()
Parse string to date LocalDate.parse(str, formatter) formatter.parse(str)
Format date to string date.format(formatter) formatter.format(date)
Key Class LocalDate, DateTimeFormatter Date, SimpleDateFormat
Thread Safety Thread-safe Not thread-safe

Always prefer the java.time package (java.time.LocalDate, java.time.format.DateTimeFormatter) for all new Java development. It's more intuitive, safer, and a vast improvement over the legacy date-time API.

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