Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Formatting Dates to Display Month and Day in Java

Tech 2

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).

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.