Sunday, November 2, 2014

GWT 2.3: Display blank column for DatePickerCell

If your Column.getValue returns null, you wouldn't be able to popup DatePickerCell.datePicker since you pass null to its datePicker.setValue method.
Here's my solution:

DatePickerCell<Object, Date> cell = new DatePickerCell(datetimeFormatter) {
     @Override
     protected void onEnterKeyDown(Context context,
                                   Element parent,
                                   Date value,
                                   NativeEvent event,
                                   ValueUpdater<Date> valueUpdater) {
         if (value == null)
             value = new Date();
         super.onEnterKeyDown(context, parent, value, event, valueUpdater);
     }
};

Friday, July 4, 2014

Java: Comparing date with today's date

Usually in Java, if you want to compare there are three methods (that I know of); using DateFormat; using Calendar; and using milliseconds since epoch. The following is how I do date comparison for each methods (starting from the slowest based on my own tests) with d as the target date:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, -5); // 5 days ago.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date d = cal.getTime();

DateFormat

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date today = sdf.parse(sdf.format(new Date));
boolean isBeforeToday = d.getTime() < today.getTime();
boolean isToday = d.getTime() == today.getTime();
boolean isAfterToday = d.getTime() > today.getTime();

Calendar

This is quite fast, so if you prefer readability, I suggest you choose this.
 
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// I think you can also use Calendar.before() & Calendar.after()...
boolean isBeforeToday = d.getTime() < cal.getTime().getTime();
boolean isToday = d.getTime() == cal.getTime().getTime();
boolean isAfterToday = d.getTime() > cal.getTime().getTime();
 

Milliseconds

 I prefer this method, which I believe the fastest. But it's the least readable...

long now = new Date().getTime();
long delta = d.getTime() - now;
boolean isBeforeToday = delta <= -86400000; // 24*60*60*1000, milliseconds in a day
boolean isToday = delta <= 0 && delta > -86400000;
boolean isAfterToday = delta > 0;

NOTE: Don't use this if the time part of java.util.Date is non-zero. :)