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
To get a java.util.Date object with the time set to 00:00:00 (midnight), you can start with a LocalDate, convert it to a ZonedDateTime at the start of the day using atStartOfDay(), convert that to an Instant, and finally use Date.from() to create the legacy Date object.
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); // Example output: 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); // Example output: 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). Note that java.util.Date stores time as UTC milliseconds, but its toString() method displays the time in the JVM's default timezone. For modern applications, consider using java.time.LocalDate or LocalDateTime directly instead of the legacy Date class.