java.time
The modern way is java.time classes. In particular, MonthDay in your case.
Please note that you must always specify Locale to determine the human language for translation in the translation of the month name.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "ddMMM" , Locale.ENGLISH ); String input = "29FEB"; MonthDay md = MonthDay.parse( input , f );
You can apply this to the year to get the LocalDate object, the date value of the entire year-month-day.
LocalDate
The LocalDate class represents a value only for a date with no time and no time zone.
The time zone is critical for determining the date. At any given moment, the date changes around the world by zone. For example, a few minutes after midnight in Paris, France is a new day, still "yesterday" in Montreal Quebec .
ZoneId z = ZoneId.of( "America/Montreal" ); LocalDate today = LocalDate.now( z );
If we look at February 29th, mark Leap Year. If this is not a leap year, then you said you want to move to the next year. But what if there is no leap year next year too? You have to keep going until you reach the Leap Year.
int yearNumber today.getYear(); LocalDate ld = null; if( md.equals( MonthDay.of( 2 , 29 ) && ( ! Year.of( today ).isLeap() ) ) { // If asking for February 29, and this is not a leap year, move to next year, per our business rule. … keep adding years until you find a year that *is* a leap year. ld = md.atYear( yearNumber + x ); } else { ld = md.atYear( yearNumber ); }
Return to the 28th
There was a special business rule on the issue of moving to the next year if the month-month is February 29 in a non-leap year. But for other people, it should be known that the default behavior in java.time is simply to return to February 28, when you ask for the 29th year, not related to the temple. No exception selected.
LocalDate february28 = MonthDay.of( 2 , 29 ) .atYear( myNonLeapYearNumber ); // 29th becomes 28th.
About java.time
The java.time framework is built into Java 8 and later. These classes supersede the nasty old legacy time classes such as java.util.Date , .Calendar and java.text.SimpleDateFormat .
The Joda-Time project, now in maintenance mode , advises switching to java.time.
To learn more, see the Oracle Tutorial . And search for qaru for many examples and explanations. JSR 310 specification .
Where to get java.time classes?
- Java SE 8 and SE 9 and later
- Built in.
- Part of the standard Java API with integrated implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and SE 7
- Most of the functionality of java.time is ported to Java 6 and 7 in ThreeTen-Backport .
- Android
The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes such as Interval , YearWeek , YearQuarter and more .