Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 LocalDate- determining the year of a yearless Feb-29 date?

My colleague and I have an interesting problem. We work with an old system that only returns date data in the format ddMMM. If the day/month is in the past for the current year, then we are to assume this date applies to next year. Otherwise it applies to the current year.

So today is 4/30/2015. If the system returned records with 12MAR, then that date translates to 3/12/2016. If the date reads 07MAY, then it translates to 5/7/2015.

However, it is unclear how to determine the year for 29FEB since it is a leap year. We cannot instantiate it with a year without the possibility of it throwing an error. We relied on a try/catch when trying to create a LocalDate off it for the current year. If it catches, we assume it belongs to next year.

Is there a more kosher way to do this?

like image 409
tmn Avatar asked Apr 30 '15 17:04

tmn


People also ask

How do I find my LocalDate year?

The year for a particular LocalDate can be obtained using the getYear() method in the LocalDate class in Java. This method requires no parameters and it returns the year which can range from MIN_YEAR to MAX_YEAR.

How do you check if a date is a leap year in Java?

The isLeapYear() method of java. time. LocalDate verifies if the year in the current object is a leap year according to the ISO proleptic calendar system rules, returns true if so, else returns false.

How do you get the month and year from LocalDate?

The idea is to use methods of LocalDate class to get the day, month, and year from the date. The getDayOfMonth() method returns the day represented by the given date, getMonth() method returns the month represented by the given date, and getYear() method returns the year represented by the given date.


1 Answers

  • Parse the value as a MonthDay, as that's what you've got.
  • If the month-day is not February 29th, just handle it as normal
  • If it is February 29th, you need to special-case it:
    • Determine whether the current year is a leap year with Year.isLeap(long)
    • If it is:
    • If it's currently on or before Feb 29th, then the result is Feb 29th of this year
    • If it's currently after Feb 29th, you need rules to apply - you could choose March 1st of next year or Feb 28th of next year
    • If it's not (a leap year this year)
    • If it's currently on or before Feb 28th, again you need to rules to apply, probably returning March 1st or Feb 28th of this year
    • If it's currently after Feb 28th, then the date logically belongs to next year...
      • If next year is a leap year, the result is presumably Feb 29th of next year
      • If next year is not a leap year, again you need a rule

That's hopefully outlined the three "odd" conditions you need to account for - we don't have enough information to tell you what to do in those conditions.

like image 195
Jon Skeet Avatar answered Nov 15 '22 01:11

Jon Skeet