package com.onaro.util.jfc.date; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Time filter for "today" ("this-day"), "this-week" and "this-month". This is a * relative time filter that its start-time is relative to the time when it was requested. */ public class TimeFilterThis implements TimeFilter { /** * Start-time fields that are zeroed. */ private static final int FIELDS_TO_CLEAN[] = new int[] { Calendar.MILLISECOND, Calendar.SECOND, Calendar.MINUTE, Calendar.HOUR_OF_DAY, }; /** * The time field to role back when the start date is requested. */ private int field; /** * Sets the time field that is zeroed in the current time to get the * start-time. * @param field Calendar.DAY_OF_MONTH Calendar.WEEK_OF_MONTH * field == Calendar.MONTH only */ public TimeFilterThis(int field) { assert field == Calendar.DAY_OF_MONTH || field == Calendar.WEEK_OF_MONTH || field == Calendar.MONTH : "Wrong field value " + field; //$NON-NLS-1$ this.field = field; } /** * Gets the start time by zeroing the selcted time-field from the current time * and zeroeing unimportant time fields. * @return the start-time */ public Date getStartTime() { Calendar start = new GregorianCalendar(); for (int i = 0; i < FIELDS_TO_CLEAN.length; ++i) { start.set(FIELDS_TO_CLEAN[i], 0); } switch (field) { case Calendar.WEEK_OF_MONTH: /** This week */ start.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); break; case Calendar.MONTH: /** This month */ start.set(Calendar.DAY_OF_MONTH, 1); break; default: //do nothing } return start.getTime(); } public Date getEndTime() { return new Date(); } public String toString() { StringBuilder s = new StringBuilder("TimeFilterThis"); //$NON-NLS-1$ s.append("[field=").append(field); //$NON-NLS-1$ s.append(", startTime=").append(getStartTime()).append(']'); //$NON-NLS-1$ return s.toString(); } /** * Test if two filters are equal. Used to prevent unneeded server request if the * filter didn't really changed. * @param obj the other filter * @return true if the filters have thesame absolute start time */ public boolean equals(Object obj) { if (obj == null || !(obj instanceof TimeFilterThis)) { return false; } TimeFilterThis other = (TimeFilterThis)obj; return field == other.field; } public int hashCode() { return field; } }