n179911
n179911

Reputation: 20341

How can I customize Java Date Format

From the java doc, the MEDIUM format is: MEDIUM is longer, such as Jan 12, 1952

https://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html

How can I customize it so that I does not display the year? And spell out "Jan" to January?

Do I need to do that myself? * chop off the string after the ',' * have a table which map the month short name (Jan) to its long name (January)?

Thank you.

Upvotes: 0

Views: 279

Answers (2)

user13634030
user13634030

Reputation:

In addition to the possibility of using SimpleDateFormat, there also exists DateTimeFormatter.

I think that DateTimeFormatter is the better option, because

  • It was introduced more recently (Java 8)
  • It is thread-save

One example:

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

public class Time {    
  public static void main(String[] args) {    
   LocalDateTime time = LocalDateTime.now();

   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd. MMM");
   String timeDate = time.format(formatter);
   System.out.println(timeDate);  
  }    
}  

This will produce something like 30. May as output.

More information can be found here and there.

Upvotes: 1

Rob Hruska
Rob Hruska

Reputation: 120456

Use SimpleDateFormat:

// For months like "Jan"
String formatted = new SimpleDateFormat("MMM dd").format(new Date());

// For months like "January"
String formatted = new SimpleDateFormat("MMMMM dd").format(new Date());

Upvotes: 11

Related Questions