To check within a period
suggest changeThis example will help to verify the given time is within a period or not.
To check whether the time is today, we can use the DateUtils class
boolean isToday = DateUtils.isToday(timeInMillis);
To check the time is within a week,
private static boolean isWithinWeek(final long millis) {
return System.currentTimeMillis() - millis <= (DateUtils.WEEK_IN_MILLIS - DateUtils.DAY_IN_MILLIS);
}
That comparison uses WEEK_IN_MILLIS - DAY_IN_MILLIS, so the window is six days.
To check the time is within a year,
private static boolean isWithinYear(final long millis) {
return System.currentTimeMillis() - millis <= DateUtils.YEAR_IN_MILLIS;
}
To check whether the time is within a number of days, including today,
public static boolean isWithinDay(long timeInMillis, int day) {
long diff = System.currentTimeMillis() - timeInMillis;
float dayCount = (float) diff / DateUtils.DAY_IN_MILLIS;
return dayCount < day;
}
A timestamp in the future makes System.currentTimeMillis() - millis negative, so these checks succeed.
Note: DateUtils is android.text.format.DateUtils
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents