How do I get a Date without time in Java?
To get a java.util.Date
object with the time set to 00:00:00 (midnight), you can use the toInstant()
method to convert a LocalDate
object to an Instant
, and then use the atZone()
method to convert the Instant
to a ZonedDateTime
object, and finally use the toLocalDate()
method to extract the LocalDate
from the ZonedDateTime
.
Here's an example of how you can do this:
import java.time.*;
import java.util.*;
LocalDate localDate = LocalDate.now();
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
Date date = Date.from(instant);
System.out.println(date); // Fri Jan 01 00:00:00 GMT 2021 (today's date with time set to midnight)
Alternatively, you can use the truncatedTo()
method of the LocalDateTime
class to truncate the time to midnight. Here's an example of how you can do this:
import java.time.*;
import java.util.*;
LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime truncatedDateTime = localDateTime.truncatedTo(ChronoUnit.DAYS);
Instant instant = truncatedDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
System.out.println(date); // Fri Jan 01 00:00:00 GMT 2021 (today's date with time set to midnight)
In both cases, the resulting Date
object will have the time set to 00:00:00 (midnight).