Formatting Dates to Display Month and Day in Java
Java provides the SimpleDateFormat class for converting and formatting dates. To display a date as "month day" (e.g., "March 15"), follow these steps.
Step 1: Instantiate a SimpleDateFormat Object Create a SimpleDateFormat instance using its constructor.
SimpleDateFormat dateFormatter = new SimpleDateFormat();
This initializes the fomratter with default locale settings.
Step 2: Define the Date Format Pattern Specify the desired output format using the applyPattern method. For "month day", use the pattern "MM月dd日".
dateFormatter.applyPattern("MM月dd日");
The pattern uses "MM" for month and "dd" for day, with Chinese characters for readability.
Step 3: Format the Date Apply the format method to a Date object to produce the fomratted string.
Date currentDate = new Date();
String formattedOutput = dateFormatter.format(currentDate);
System.out.println("Formatted date: " + formattedOutput);
This outputs the current date in the specified format, such as "03月15日".
Complete Example Here is a full code snippet that combines all steps:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat();
formatter.applyPattern("MM月dd日");
Date now = new Date();
String result = formatter.format(now);
System.out.println(result);
}
}
Run this program to see the formatted date printed too the console.
Notes on SimpleDateFormat
- SimpleDateFormat is not thread-safe; avoid sharing instances across multiple threads with out synchronization.
- For newer Java versions (8 and above), consider using the java.time package (e.g., DateTimeFormatter) for improved functionality and thread safety.
- Customize the pattern further by adjusting symbols (e.g., use "M" for month with out leading zeros).