AndreaNobili AndreaNobili - 9 days ago 6
Java Question

What is a smarter way to check if a Joda-Time DateTime object does not represent the last day of the year?

I am using Joda-Time and I would like to check if a specific date is not the last day of a year (in other words the date should not be 31/12/XXXX). It should work for any year.

To implement this check I have done something like this:

DateTime dataSecondoMovimento = new DateTime(mappaQuote.get(2).getDatariferimentoprezzo());

if(!(dataSecondoMovimento.getMonthOfYear() == 12 && dataSecondoMovimento.getDayOfMonth() == 31)) {
System.out.println("It is not the end of year !!!");
}


So basically I am checking if the month is not December and if the day is not 31 (both have to be true for it not to be the last day of year). I think that this should work fine.

My question: does Joda-Time provide a neater way of doing this? Does there exist a method of checking if a specific date is the last day of the year?

Answer

Currently Joda Time don't have direct implementation of getLastDayOfYear(), we have to use logical way to handle the last day of year, one way you tried or you can use alternate way as below

 public int getDayOfYear() { //This is library method
    return getChronology().dayOfYear().get(getMillis());
}

if(!getDayOfYear() <=365 ||!getDayOfYear() <=366) { //Considering leap year
System.out.println("It is not the end of year !!!");
}
Comments