To check within a period

suggest change

This 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents