You can format dates in Java using the SimpleDateFormat class, which is part of the java.text package. This class allows you to specify patterns describing the formatting and parsing of date and time objects.
Here’s a step-by-step guide:
Example of Formatting Dates with SimpleDateFormat
package org.kodejava.text;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
// Create an instance of SimpleDateFormat
// Specify the desired pattern
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
// Get the current date
Date currentDate = new Date();
// Format the date
String formattedDate = simpleDateFormat.format(currentDate);
// Print the result
System.out.println("Formatted Date: " + formattedDate);
}
}
Common Patterns for Date and Time Formatting
Here are some of the most commonly used patterns:
| Symbol | Description | Example |
|---|---|---|
y |
Year | 2025 |
M |
Month in year | 08 or August |
d |
Day of the month | 02 |
h |
Hour in AM/PM (1-12) | 3 |
H |
Hour in day (0-23) | 15 |
m |
Minute in hour | 45 |
s |
Second in minute | 30 |
S |
Millisecond | 978 |
E |
Day of the week | Tue |
D |
Day of the year | 214 |
z |
Time zone | PDT |
Z |
Time zone offset | -0700 |
You can mix and match these symbols to create a pattern that suits your needs.
Example with Custom Pattern
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, MMM dd, yyyy hh:mm a");
Date date = new Date();
System.out.println("Custom Formatted Date: " + dateFormat.format(date));
Output:
Custom Formatted Date: Saturday, Aug 02, 2025 10:30 AM
Notes:
-
Thread Safety:
SimpleDateFormatis not thread-safe. If you need to use it in a multithreaded environment, you should manage synchronization or usejava.time.format.DateTimeFormatter, which is thread-safe and introduced in Java 8. -
For Java 8 and Later:
If you’re using Java 8 or later, consider using the newjava.timeAPI (DateTimeFormatter) for better clarity and thread safety.
