How to remove Hour, Minute, and Second from Epoch timestamp

Churro picture Churro · Oct 1, 2013 · Viewed 16.6k times · Source

I need to write a function that accepts a java.util.Date and removes the hours, minutes, and milliseconds from it USING JUST MATH (no Date formatters, no Calendar objects, etc.):

private Date getJustDateFrom(Date d) {
    //remove hours, minutes, and seconds, then return the date
}

The purpose of this method is to get the date from a millisecond value, without the time.

Here's what I have so far:

private Date getJustDateFrom(Date d) {
    long milliseconds = d.getTime();
    return new Date(milliseconds - (milliseconds%(1000*60*60)));
}

The problem is, this only removes minutes and seconds. I don't know how to remove hours.

If I do milliseconds - (milliseconds%(1000*60*60*23)), then it goes back to 23:00 hrs on the previous day.

EDIT:

Here's an alternative solution:

public static Date getJustDateFrom(Date d) {
    Calendar c = Calendar.getInstance();
    c.setTime(d);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    return c.getTime();
}

Will this solution be affected by time zone differences between the client/server sides of my app?

Answer

Mark Bailey picture Mark Bailey · Oct 1, 2013

There are 24 hours in a day. Use milliseconds%(1000*60*60*24).