杰瑞科技汇

yyyymmddhhmmss在Java中如何处理时间?

Of course! In Java, formatting a date and time into the yyyyMMddHHmmss format is a common task. This format is often used for logging, generating unique filenames, or timestamps.

yyyymmddhhmmss在Java中如何处理时间?-图1
(图片来源网络,侵删)

The modern and recommended way to do this is using the java.time package, introduced in Java 8. I'll show you the best approach first, followed by the older SimpleDateFormat method for completeness.

The Modern Approach (Java 8+): java.time

The java.time package is the current standard for date-time handling in Java. It's more powerful, thread-safe, and easier to use than the older classes.

The key class for formatting is DateTimeFormatter.

Example Code

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class YyyyMmDdHhMmSsFormatter {
    public static void main(String[] args) {
        // 1. Get the current date and time
        LocalDateTime now = LocalDateTime.now();
        // 2. Define the desired format pattern
        //    y = year, M = month, d = day
        //    H = hour (0-23), m = minute, s = second
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 3. Format the current date and time using the formatter
        String formattedDateTime = now.format(formatter);
        // 4. Print the result
        System.out.println("Current Date and Time: " + now);
        System.out.println("Formatted Timestamp:   " + formattedDateTime);
    }
}

Output

Current Date and Time: 2025-10-27T10:30:55.123
Formatted Timestamp:   20251027103055

Breakdown of the Pattern ("yyyyMMddHHmmss")

Character Meaning Example
yyyy 4-digit year 2025
MM 2-digit month (01-12) 10
dd 2-digit day of the month (01-31) 27
HH 2-digit hour in 24-hour format (00-23) 10
mm 2-digit minute (00-59) 30
ss 2-digit second (00-59) 55

Important Note on Case Sensitivity:

yyyymmddhhmmss在Java中如何处理时间?-图2
(图片来源网络,侵删)
  • MM is for Month.
  • mm is for Minute.
  • HH is for Hour in 24-hour format.
  • hh is for Hour in 12-hour format (which you usually don't want for this format).

The Older Approach (Pre-Java 8): SimpleDateFormat

Before Java 8, SimpleDateFormat was the standard class. It's important to know that SimpleDateFormat is not thread-safe. You should not create a new instance of it every time in a high-concurrency application. Instead, you should declare it as static final if you must use it.

Example Code

import java.text.SimpleDateFormat;
import java.util.Date;
public class LegacyYyyyMmDdHhMmSsFormatter {
    // IMPORTANT: Declare formatter as static final if you use this class in a multi-threaded environment.
    // It is NOT thread-safe if you create a new instance for each call.
    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");
    public static void main(String[] args) {
        // 1. Get the current date and time
        Date now = new Date();
        // 2. Format the date using the formatter
        //    The format() method is synchronized, but the formatter object itself is not.
        String formattedDateTime = FORMATTER.format(now);
        // 3. Print the result
        System.out.println("Current Date and Time: " + now);
        System.out.println("Formatted Timestamp:   " + formattedDateTime);
    }
}

Output

Current Date and Time: Fri Oct 27 10:30:55 CEST 2025
Formatted Timestamp:   20251027103055

How to Parse (Read) the String Back into a Date/Time Object

Often, you'll need to do the reverse: convert a string like "20251027103055" back into a date-time object.

Using java.time (Recommended)

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class ParseYyyyMmDdHhMmSs {
    public static void main(String[] args) {
        String timestampString = "20251027103055";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // Parse the string into a LocalDateTime object
        LocalDateTime dateTime = LocalDateTime.parse(timestampString, formatter);
        System.out.println("Parsed String: " + timestampString);
        System.out.println("LocalDateTime: " + dateTime);
        System.out.println("Formatted back: " + dateTime.format(formatter)); // Verification
    }
}

Output

Parsed String: 20251027103055
LocalDateTime: 2025-10-27T10:30:55
Formatted back: 20251027103055

Using SimpleDateFormat (Legacy)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class LegacyParseYyyyMmDdHhMmSs {
    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyyMMddHHmmss");
    public static void main(String[] args) {
        String timestampString = "20251027103055";
        try {
            // Parse the string into a Date object
            Date date = FORMATTER.parse(timestampString);
            System.out.println("Parsed String: " + timestampString);
            System.out.println("Date: " + date);
        } catch (ParseException e) {
            System.err.println("Failed to parse the date string: " + e.getMessage());
        }
    }
}

Summary: Which One Should You Use?

Feature java.time (Modern) SimpleDateFormat (Legacy)
Recommendation Strongly Recommended Use only for legacy code
Thread Safety All classes are immutable and thread-safe. Not thread-safe. Must be static final.
API Fluent, intuitive, and powerful. Clumsy and error-prone.
Key Classes LocalDateTime, DateTimeFormatter SimpleDateFormat, Date
Time Zone Explicit handling with ZonedDateTime. Implicit and often confusing.

Always prefer the java.time API for any new Java development. It is the future-proof and standard way to handle dates and times.

yyyymmddhhmmss在Java中如何处理时间?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇