0

I'm trying to round down to the nearest day/minute/hour/four hours and get the millisecond timestamp - to work on data that needs to be stored in lumps of those sizes (but can round up, only down).

I have tried this:

    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int unroundedHour = calendar.get(Calendar.DATE);
    int mod = unroundedHour % 1;
    calendar.add(Calendar.DATE, unroundedHour == 0 ? -1 : -mod);
    return calendar.getTimeInMillis();

However when converting the output of this back to a human readable format (to ensure it is working), the output is:

Sun Sep 20 16:40:28 BST 2015

How can I round down to the nearest timeunit and get the time in millis?

EDIT:

Not a duplicate, all provided links round to nearest, not down.

EDIT 2:

Partial answer, this works for getting the beginning of the day:

private long getDay()
{
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(getStartOfDay(date));
    return calendar.getTimeInMillis();
}

private static Date getStartOfDay(Date date) {
    return DateUtils.truncate(date, Calendar.DATE);
}
  • Also duplicate of [this](http://stackoverflow.com/q/17393764/642706) and [this](http://stackoverflow.com/q/7040409/642706) . – Basil Bourque Sep 20 '15 at 15:56
  • No, it is not. Neither of those are looking to round down - I have already looked at both of these :) – William Dunne Sep 20 '15 at 16:19
  • So choose the [ROUND_DOWN](http://www.rakeshv.org/docs/java/rakeshv/org/rakeshv/utils/Calendar.html#ROUND_DOWN) option in the library shown in the second link. – Basil Bourque Sep 20 '15 at 20:06

0 Answers0