How to remove Hour, Minute and Second from Epoch Timestamp

I need to write a function that accepts java.util.Dateand removes hours, minutes and milliseconds from it. USING JUST MATH (without date formats, without 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 a date from a millisecond value without time.

Here is what I still have:

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

The problem is that it only removes minutes and seconds. I do not know how to remove a watch.

If I do milliseconds - (milliseconds%(1000*60*60*23)), then he returns to 23:00 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 decision depend on time zone differences between the client and server sides of my application?

+4
3

24 . % (1000 * 60 * 60 * 24).

+8

.

, (1970-01-01 00: 00: 00.000 UTC, ). + .

, , . , Date.getTime() - - , .

.

+2

apache commons lang DateUtils.

For example, if you had a date and time on March 28, 2002 13: 45: 01.231, if you passed with Calendar.HOUR, it will return on March 28, 2002 13: 00: 00 000. If it was passed using Calendar.MONTH, return 1 Mar 2002 0: 00: 00.000.

Date newDate = DateUtils.truncate(new Date(1408338000000L), Calendar.DAY_OF_MONTH);

You can download commons lang jar at http://commons.apache.org/proper/commons-lang/

+1
source

All Articles