Java SimpleDateFormat Class

SimpleDateFormatis a class in Java used for formatting and parsing date and time, belonging to thejava.textpackage. It allows you to convert date objects (Date) into strings in a specific format, or parse formatted date strings back into date objects.


Basic Usage

1. Creating a SimpleDateFormat Object

To useSimpleDateFormat, you first need to create an instance and specify a date format pattern:

Example

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        // Create a SimpleDateFormat object and specify the format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       
        // Get the current date and time
        Date now = new Date();
       
        // Format the date as a string
        String formattedDate = sdf.format(now);
        System.out.println("Current time: " + formattedDate);
    }
}

The output is:

当前时间: 2025-05-01 11:35:07

2. Common Format Pattern Symbols

The following are common format pattern symbols:

Symbol Meaning Example
yyyy Four-digit year 2023
MM Two-digit month 01-12
dd Two-digit day 01-31
HH Hour in 24-hour format 00-23
mm Minute 00-59
ss Second 00-59
E Day of the week Mon, Tue, etc.
a AM/PM marker AM or PM

Date Formatting

willDateFormat the object as a string:

Example

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEEE a hh:mm:ss");
Date now = new Date();
System.out.println(sdf.format(now));
// Example output: 2023-11-15 Wednesday PM 03:45:22

Date Parsing

Parse the formatted date string into aDateobject:

Example

try {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String dateString = "2023-11-15";
    Date date = sdf.parse(dateString);
    System.out.println(date);
    // Output: Wed Nov 15 00:00:00 CST 2023
} catch (ParseException e) {
    e.printStackTrace();
}

Note: parsing may throwParseException, so exception handling is required.


Thread Safety Issue

SimpleDateFormatIt is not thread-safe. If the sameSimpleDateFormatinstance is shared in a multi-threaded environment, it may cause problems. Solutions:

  1. Create a new instance each time it is used (lower performance)
  2. UseThreadLocalto save an instance for each thread
  3. Use Java 8'sDateTimeFormatter(recommended)

Example

// Solution using ThreadLocal
private static final ThreadLocal<SimpleDateFormat> dateFormat =
    ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

// Usage
String formattedDate = dateFormat.get().format(new Date());

Java 8 Alternative

In Java 8 and later versions, it is recommended to usejava.timeclasses in the package:

Example

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Create a formatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
       
        // Get the current time and format it
        LocalDateTime now = LocalDateTime.now();
        String formattedDate = now.format(formatter);
        System.out.println("Current time: " + formattedDate);
       
        // Parse the string into a date-time
        LocalDateTime parsedDate = LocalDateTime.parse("2023-11-15 14:30:00", formatter);
        System.out.println("Parsed time: " + parsedDate);
    }
}

DateTimeFormatterIt is thread-safe, performs better, and is recommended for use in new projects.


Summary

  1. SimpleDateFormatUsed for date formatting and parsing
  2. Specify the date format through pattern strings
  3. Not thread-safe; you need to pay attention to its use in multi-threaded environments
  4. For Java 8 and above, it is recommended to useDateTimeFormatter

By masteringSimpleDateFormat, you can flexibly handle the conversion needs of various date and time formats in Java programs.

The following are common methods of the java.text.SimpleDateFormat class:

Constructors

Method Description
SimpleDateFormat() Constructs an object using the default pattern and the default locale's date format symbols
SimpleDateFormat(String pattern) Constructs an object using the given pattern and the default locale's date format symbols
SimpleDateFormat(String pattern, Locale locale) Constructs an object using the given pattern and the given locale's date format symbols

Common Format Pattern Symbols

Symbol Meaning Example
y year yyyy → 2023
M month MM → 07, MMM → Jul, MMMM → July
d Day of the month dd → 15
H Hour (0-23) HH → 14
h Hour (1-12) hh → 02
m Minute mm → 30
s second ss → 45
S Millisecond SSS → 789
E Day of the week EEE → Mon, EEEE → Monday
a AM/PM marker a → PM
z Time zone z → CST, zzzz → China Standard Time

Core Methods

Method Description
String format(Date date) Formats a Date into a date/time string
Date parse(String source) Parses text from a string to produce a Date object
void applyPattern(String pattern) Applies a new date and time pattern
String toPattern() Returns the current date and time pattern string
void setTimeZone(TimeZone zone) Sets the time zone
TimeZone getTimeZone() Gets the time zone
void setLenient(boolean lenient) Sets whether parsing is lenient (default true)
boolean isLenient() Determines whether parsing is lenient
Other Extensions