Fighting with computers

Computers are not always friendly.

Monday, February 21, 2011

Annoying Java behavior


A recent class exercise required students to create a program that handle a list of scheduled events. While I was not suggesting a specific approach, I used java.util.Date for handling the time.

Events happening in the future can be scheduled by adding a certain value to the current time. System.getCurrentMilis() gives you the value of milliseconds since January 1, 1970 00:00:00 GMT.

When creating a new Date object, the default value is the current time, but any number of milliseconds could be used to create any time into the past or the future. I was using this approach for scheduling future events. Later, I was checking, every second, if any of the future events on my list was already due. Unfortunately, I was using .equals() function for that but only a few times worked as expected.

The problem was that .equals() function works on a millisecond time base. If the two values compared are not exactly the same number of milliseconds since January 1, 1970 00:00:00 GMT then the answer will always be false.

If you are like me, you might be expecting two dates to be the equal if date, hours, minutes and seconds are the same. The simple solution is not to compare the two Date objects but the strings you obtain with the .toString() function of each one.

This site also seems not happy about Date class.

2 Comments:

  • At 4:34 am, Blogger klondike said…

    There is another way to do that:
    You take the current date d. And the event date d'.
    Once d.after(d') the date is due, so now all you have to do is mark the event as notified :P

     
  • At 8:31 am, Blogger Miguel Sánchez said…

    Thanks Klondike. I haven't noticed .after() method.

     

Post a Comment

<< Home