18

I have a variable of the type java.util.Date.

How can I set the time part to 00:00:00?

I am not allowed to use an Apache Commons library or JodaTime. The java.util.Calendar is probably my only option.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
  • 1
    @AnthonyKong FYI, you can convert [Joda-Time](http://www.joda.org/joda-time/) [DateTime](http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html) objects to java.util.Date objects ([`toDate`](http://www.joda.org/joda-time/apidocs/org/joda/time/base/AbstractInstant.html#toDate())), and back again. So you can make use of Joda-Time for calculations without disturbing other existing code. – Basil Bourque Dec 06 '13 at 07:05
  • For new readers to the question I recommend you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And other classes from the same API depending on your precise requirements. – Ole V.V. Apr 07 '21 at 11:00
  • In some time zones dates exist that haven’t got any 00:00:00. You will have to make yourself satisfied with getting the first moment of the day. – Ole V.V. Apr 07 '21 at 11:01

5 Answers5

37

To remove time from the Date object completely, you could use this:

public static Date removeTime(Date date) {    
        Calendar cal = Calendar.getInstance();  
        cal.setTime(date);  
        cal.set(Calendar.HOUR_OF_DAY, 0);  
        cal.set(Calendar.MINUTE, 0);  
        cal.set(Calendar.SECOND, 0);  
        cal.set(Calendar.MILLISECOND, 0);  
        return cal.getTime(); 
    }

Pass into the method the Date object that you want to modify and it will return a Date that has no hours/minutes etc.

If changing the Date object itself isn't required, use SimpleDateFormat. Set the format the way you want ie. remove hours/minutes. Then call the format method and pass in the Date object you want changed.

SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy");
System.out.println(sdf.format(yourDate));
Sionnach733
  • 4,686
  • 4
  • 36
  • 51
5

tl;dr

If you meant midnight in UTC in an old legacy java.util.Date object…

java.util.Date.from(
    OffsetDateTime.of( 
        LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
        LocalTime.MIN ,
        ZoneOffset.UTC
    ).toInstant()
)

If possible, discard the legacy Date portion above and just use the modern java.time.OffsetDateTime or java.time.Instant object…

OffsetDateTime.of( 
    LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
    LocalTime.MIN ,
    ZoneOffset.UTC
).toInstant()

If you meant midnight in a particular time zone rather than UTC…

LocalDate.now()
         .atStartOfDay()

Better to specify your desired/expected time zone than rely implicitly on current default.

LocalDate.now( ZoneId.of( "Pacific/Auckland" )  )
         .atStartOfDay( ZoneId.of( "Pacific/Auckland" ) )

Details

Caution: Not every day in every time zone has a time of 00:00:00. Daylight Savings Time can jump to 1 AM, eliminating a midnight.

java.time

Using java.time classes that supplant the troublesome old legacy date-time classes such as java.util.Date and .Calendar.

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( z );
ZonedDateTime zdt = localDate.atStartOfDay( z );

Convert to/from legacy classes

You should stick to the modern java.time classes whenever possible. But if you must have have instances of the old legacy classes, you can convert to/from java.time. Look to new methods added to the old classes.

Calendar myLegacyCal = GregorianCalendar.from( zdt ) ;

Date myLegacyDate = Date.from( zdt.toInstant() ) ;

If you want a java.util.Date, which is always in UTC time zone, to have a time-of-day of 00:00:00, use OffsetDateTime with the constant ZoneOffset.UTC.

OffsetDateTime odt = OffsetDateTime.of( localDate , LocalTime.MIN , ZoneOffset.UTC ) ;
Date myLegacyDate = Date.from( odt.toInstant() ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes. This section left intact as history.

Use Joda-Time 2.3, with a method for this very purpose: withTimeAtStartOfDay().

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;

DateTime now = new DateTime();
DateTime firstMomentOfToday = now.withTimeAtStartOfDay();

System.out.println( "now: " + now );
System.out.println( "firstMomentOfToday: " + firstMomentOfToday );

When run…

now: 2013-12-05T23:00:23.785-08:00
firstMomentOfToday: 2013-12-05T00:00:00.000-08:00
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • The question is specifically looking for a DATE – Max Alexander Hanna Jul 25 '17 at 15:26
  • @MaxAlexanderHanna Nope. Reread the Question. The author considered and excluded two 3rd-party libraries. Then the last sentence suggests using `Calendar` class. So I can safely assume (a) they are open to an alternative, new classes built into Java, and (b) they are simply operating in ignorance, not yet having been informed of the java.tine classes available to them. – Basil Bourque Jul 25 '17 at 16:34
  • the question is asking to set the time in a java.util.date object isnt it ? – Max Alexander Hanna Jul 25 '17 at 16:38
  • @MaxAlexanderHanna I already pointed you to relevant parts of the Question, written in plain text. Furthermore, we have many hundreds of Java Date/Calendar class questions that have now been answered with **java.time classes that directly supplant the legacy classes** as directed by Sun, Oracle, and the JSR community. There comes a time when the only responsible advice is to abandon your [Yugo](https://en.m.wikipedia.org/wiki/Zastava_Koral) and use the Honda sitting in your driveway. Nevertheless, I did add some verbiage and code example for converting to/from legacy objects. – Basil Bourque Jul 25 '17 at 16:49
  • thats more to the point then. people get here when trying to look for the answer to the question at hand, not some random answer youre trying to come up with by yourself. Answer what was asked dont answer what was not asked and what you believe is a better question. you got upvoted for the good post now. – Max Alexander Hanna Jul 25 '17 at 17:05
3

In Java 8 'java.time.LocalDate.atStartOfDay()' can be used too:

    Date date = new Date();
    Instant inst = date.toInstant();
    LocalDate localDate = inst.atZone(ZoneId.systemDefault()).toLocalDate();
    Instant dayInst = localDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
    Date day = Date.from(dayInst);
Kayvan Tehrani
  • 3,070
  • 2
  • 32
  • 46
  • 3
    Correct answer. I just want to point out that we normally don't mix the modern java.time classes with the troublesome old legacy date-time classes such as `Date`. So ideally one would stop once the `Instant` object was obtained. Only convert to `Date` if absolutely necessary such as interacting with some older code not yet updated to java.time. – Basil Bourque Mar 29 '17 at 07:29
1

Like @Sionnach733, to remove time from Date, you can write this function for your DateTimeUtils with clear:

public static Date getDateOnly(final Date input) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(input);
        cal.clear(Calendar.HOUR_OF_DAY);
        cal.clear(Calendar.MINUTE);
        cal.clear(Calendar.SECOND);
        cal.clear(Calendar.MILLISECOND);
        return cal.getTime();
    }
Toi Nguyen
  • 413
  • 1
  • 6
  • 17
1

Latest version courtesy of Ole.V.V

import java.time.*;

Instant dInst = LocalDate.of(1980, Month.JANUARY, 8).atStartOfDay(ZoneOffset.UTC).toInstant();
long milli = dInst.toEpochMilli();
mplungjan
  • 169,008
  • 28
  • 173
  • 236