tl;dr
MonthDay.of( Month.JANUARY , 23 )
.toString()
…or…
MonthDay.of( Month.JANUARY , 23 )
.format( DateTimeFormatter.ofPattern( "dd MMM" ) )
MonthDay
If you want to represent a month and day-of-month without any year, use the MonthDay
class. Built just for that purpose.
The standard ISO 8601 format for a month and day is "--MM-DD". Similar to the date format of "YYYY-MM-DD" but with a hyphen replacing the year.
The java.time classes use ISO 8601 formats by default when parsing/generating Strings. So no need to specify a formatting pattern for such strings. For your custom format, we must define a formatter. I suggest sticking with the ISO 8601 formats whenever possible.
MonthDay md = MonthDay.of( 12 , 23 );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM" );
String output = md.format( f );
md.toString(): --12-23
output: 23-Dec
See live code in IdeOne.com.
Your Question contradicts itself, at one point showing a hyphen in your desired format but in another, a SPACE. If you want the SPACE, use DateTimeFormatter.ofPattern( "dd MMM" )
.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
- Java SE 8 and SE 9 and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.