Doc Holiday
Doc Holiday

Reputation: 10254

Java Calendar/Date issue

I'm building a list of Months I'm using as headers for a table in a JSP.

What I’m doing is comparing what the month is I'm getting from the database and iterating or "trying" to all the way up to that month. In the case, the Month is November

The problem is I'm only able to build a list from October 2012 to October 2013

My logic looks sound, I'm not sure what else I can try.

Starting point and compare..From the database the key is

int effortYear = 2013
Calendar max = Calendar.getInstance();
         max.set(effortYear,8,1,0,0,0);
   for (ItemUnitBean item:  scheduledBeans)

       {
             ItemUnitBean bean = new ItemUnitBean();
          for(Entry<Date, ItemPhasing> en : item.getScheduledItemByMonth().entrySet() )
           {
System.out.println( "KEY= " + en.getKey() );  // KEY =2013-11-01 
  if ( en.getKey().compareTo(max.getTime()) > 0 ) 
              {
                    max.setTime(en.getKey());
              }

           }
          finalScheduledBeans.add(bean);
       }

Now Building the list:

TreeSet<Date> scheduledMonthList = new TreeSet<Date>();
  Calendar temp = Calendar.getInstance();
         temp.set(effortYear-1,9,1,0,0,0);

         do 
         {
             scheduledMonthList.add(temp.getTime());
             System.out.println("montList= " + temp.getTime()  );
             temp.add( Calendar.MONTH, 1 );


         }  while( temp.compareTo(max) <= 0 );

This is what the logger spits out:

enter image description here

Can anyone see why Nov is not being added to the list??

Upvotes: 3

Views: 284

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 340230

tl;dr

LocalDate.parse( "2013-11-01" ).isAfter( latest )

java.time

You are using terribly-flawed date-time classes that are now legacy. Use only the modern java.time classes defined in JSR 310, and built into Java 8+.

For a date-only value, without time-of-day, and without time zone, use LocalDate.

LocalDate date = LocalDate.parse( "2013-11-01" ) ;

Compare, to get the largest.

LocalDate latest = LocalDate.MIN ; 
for ( … )
{
    LocalDate date = … ; 
    if ( date.isAfter ( latest ) { latest = date ; }
}

Or use a stream.

LocalDate latest = 
    listOfDates
    .stream()
    .max()
    .orElseThrow( NoSuchElementException :: new )  // If the list were empty.
;

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692231

You're starting your loop with a calendar set to now, and where you reset the year, month, date, hour, minute and second. But you don't set the milliseconds to 0.

So once you reach October, you add one month, and obtain November + some milliseconds. And November + some millisesonds is bigger than November + 0 millisecond.

Upvotes: 4

Related Questions