Calculating a day with a date

From this date, I need to calculate the midnight of my day. Here is what I came up with. It is so ugly that I think there should be a better way.

private Date day(Date creation) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(creation);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

Suggestions?

Kent

+5
source share
8 answers

You should consider the built-in date API. Instead, use the Joda Date and Time API.

Here you can replace your method.

private Date day(Date creation) {
    return new DateMidnight(creation).toDate();
}

Here is a simple test:

public static void main(String[] args) {
    final Date creation = new Date();
    final Date midnight = new Foobar().day(creation);
    System.out.println("creation = " + creation);
    System.out.println("midnight = " + midnight);
}

Output:

creation = Sun May 31 10:09:38 CEST 2009    
midnight = Sun May 31 00:00:00 CEST 2009
+7
source

JODA may have a better solution due to another library dependency. I look at its DateMidnight property . I wish I could respond more authoritatively, but I am not a JODA user.

+5
source

, , . , () .

UTC, :

public static void main(String[] argv)
throws Exception
{
    final long MILLIS_PER_DAY = 24 * 3600 * 1000L;

    long midnightUTC = (System.currentTimeMillis() / MILLIS_PER_DAY) * MILLIS_PER_DAY;
}

. "" . , , - , , "" 3 , .

+2

JODA - , , JSR-310 JDK (, 1.7, 1.8).

, , , .

import static java.util.Calendar.*;

...

private static final List<Integer> TIME_FIELDS = 
    Arrays.asList(HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND);

private Date day(Date creation) {
     Calendar c = getInstance();
     c.setTime(creation);
     for(int field : TIME_FIELDS) c.set(field, 0);
     return c.getTime();
}

. , ( Calendar FIELD_COUNT, , - ), JDK .

+1

date4j:

DateTime start = dt.getStartOfDay();
+1

, - . ,

  • " ", Nachum Dershowitz Ed Reingold .

  • , . , - , .

, Date Calendar, , .

0

Java , set method, , . , , , , -. , .

0

This is just a complement to the originally published code. It sets the year, month, and day in the new GregorianCalendar object, instead of clearing everything except Year, Month, and Day in a calendar variable. This has not improved much, but I think it’s clearer to say which fields you copy and not which fields you ignore.

public Date day(Date creation) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(creation);
    return new GregorianCalendar(
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)).getTime();
}

Personally, I think I will go with the Jod library offered by others.

0
source

All Articles