Monday, July 27, 2009

Java Date: beginning or end of day

Symptom



When specifying a date range for a search, the result I expected didn't show up. I entered the same day as the beginning and the end of the search range. This was the same date found in my expected result.


Problem



The date selector I was using picked some arbitrary time of day. It subsequently compared my potential results to that exact time. Since my expected result was merely on the same day, it did not show up.


Solution



You will want to set the time of the start day to be the start of the day. Likewise, you will want the end day to be the end of the day. This way, your search will include every result in the start day and the end day. The code below will accept any Date object set the time to the beginning or end of the day.




public static Date beginningOfDay(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, 0 - calendar.get(Calendar.HOUR_OF_DAY));
calendar.add(Calendar.MINUTE, 0 - calendar.get(Calendar.MINUTE));
calendar.add(Calendar.SECOND, 0 - calendar.get(Calendar.SECOND));
calendar.add(Calendar.MILLISECOND, 0 - calendar.get(Calendar.MILLISECOND));
return calendar.getTime();
}

public static Date endOfDay(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, 23 - calendar.get(Calendar.HOUR_OF_DAY));
calendar.add(Calendar.MINUTE, 59 - calendar.get(Calendar.MINUTE));
calendar.add(Calendar.SECOND, 59 - calendar.get(Calendar.SECOND));
calendar.add(Calendar.MILLISECOND, 999 - calendar.get(Calendar.MILLISECOND));
return calendar.getTime();
}

Monday, September 8, 2008

Styles messed up, no navigation, or JavaScript error. Take your pick.

Symptom


This was a very strange problem to encounter. I had a commandLink that seemed to work fine in IE6. In Firefox 2, however, the page I linked to was rendered without any styles or ajax functionality. Then, in IE7, the link did not even navigate to the page. It did nothing.


Problem


Using Firebug, I saw that there were multiple errors concerning illegal characters. This provided zero insight. IE7 just gave me an object undefined error in some obscure place. IE6 actually gave me an error as well, even though it immediately went away when the page finished rendering. Eventually it dawned on me. I was using an a4j:commandLink even though I was navigating to another page. Dumb.


Solution


I changed my a4j:commandLink's to h:commandLink's. Apparently returning a string that results in a navigation-rule produces unexpected results when applied to an a4j:commandLink.