There's a class for that!
java.time.MonthDay
Rather than roll-your-own, use the MonthDay
class built into Java 8 and later. For Java 6 & 7, use the back-port.
MonthDay[] mds = new MonthDay[5] ;
mds[0] = MonthDay.of( 7 , 22 ) ;
mds[1] = MonthDay.of( Month.AUGUST , 25 ) ;
mds[2] = MonthDay.of( Month.JUNE , 25 ) ;
mds[3] = MonthDay.of( Month.SEPTEMBER , 28 );
mds[4] = MonthDay.of( 9 , 5 ) ;
Arrays.sort(mdates);
Better to use Java Collections generally.
List< MonthDay > mds = new ArrayList<>() ;
mds.add( MonthDay.of( 7 , 22 ) ) ;
mds.add( MonthDay.of( Month.AUGUST , 25 ) ) ;
mds.add( MonthDay.of( Month.JUNE , 25 ) ) ;
mds.add( MonthDay.of( Month.SEPTEMBER , 28 ) ) ;
mds.add( MonthDay.of( 9 , 5 ) ) ;
Collections.sort( mds ) ;
Strings
I want to write a class so that I can print the date in dd/mm format,
To learn about writing the class, check out the source code in the OpenJDK project.
As for generating text representing that month-day class, simply call toString
to generate a value in standard ISO 8601 format. I strongly suggest use these standard formats for logging, storing, and exchanging date-time values as text.
MonthDay.of( Month.JUNE , 25 ) )
.toString()
--06-25
For presentation to the user, specify your desired format with DateTimeFormatter
class. Search Stack Overflow for more info, as this has been covered many many times already.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
String output = mds.get( 0 ).format( f ) ; // Generate string in custom format.
25/06
Dump to console.
System.out.println( "mds: " + mds ) ;
System.out.println( "mds.get( 0 ) = " + mds.get( 0 ) + " | output: " + output ) ;
See this code run live at IdeOne.com.
mds: [--06-25, --07-22, --08-25, --09-05, --09-28]
mds.get( 0 ) = --06-25 | output: 25/06
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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.