Thursday, September 06, 2007

Yesterday or Tomorrow

Thinking about days and nights and the good old Java 'when are we now?' classes Date and Calendar. If I want to know if something is earlier than today...


public boolean isBeforeToday(Date date) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Date startOfToday = cal.getTime();
return date.before(startOfToday);
}


It feels pretty clunky. Likewise for after today...

public boolean isAfterToday(Date date) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);

Date endOfToday = cal.getTime();
return date.after(endOfToday);
}

What if I want to know if a date is within the day before today (otherwise known as yesterday)...

public boolean isYesterday(Date date) {
// get a calendar for yesterday
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_YEAR, -1);

// and one for the test date
Calendar cal = Calendar.getInstance();
cal.setTime(date);

// true if year and day of year are equal to yesterday
return (yesterday.get(Calendar.YEAR) == cal.get(Calendar.YEAR))
&& (yesterday.get(Calendar.DAY_OF_YEAR) == cal
.get(Calendar.DAY_OF_YEAR));
}

Long winded? So I got to thinking about some possible short cuts and wondered what the following could give us...

public long getOrdinalDayForDate(Date date) {
final long MILLISECS_IN_DAY = 1000 * 60 * 60 * 24;
return date.getTime() / MILLISECS_IN_DAY;
}

By giving each date an index, day number from the first day of 1970, we can have...

public boolean isToday(Date date) {
return getOrdinalDayForDate(date) == getOrdinalDayForDate(new Date());
}

public boolean isYesterday(Date date) {
return getOrdinalDayForDate(date) == (getOrdinalDayForDate(new Date())-1);
}

public boolean isTomorrow(Date date) {
return getOrdinalDayForDate(date) == (getOrdinalDayForDate(new Date())+1);
}


Am I on the right track with this?

Labels:

0 Comments:

Post a Comment

<< Home