The Java LocalDate atStartOfDay() method is used to combine the date with the time of midnight at the start of this date. It means if we wish to get a date of 20, August 2020 with midnight time then we can use the atStartOfDay() method and it will return date as 2020-08-20T00:00. The syntax of the method is here.
public LocalDateTime atStartOfDay()
This method belongs to Java 8 LocalDate class which is stored into java.time package and method description are given below.
It does not take any argument.
It returns the local date-time(LocalDateTime object) of midnight at the start of this date.
No Exception
This method is added to Java 1.8.
In this example, the atStartOfDay() method is used to get date with time of midnight.
import java.time.LocalDate;
import java.time.LocalDateTime;
/*
* Example of atStartOfDay() method of LocalDate class
*/
public class JExercise {
public static void main(String[] args) {
// Take a date
LocalDate date = LocalDate.parse("2020-08-20");
// Displaying date
System.out.println("date : "+date);
// Using atStartOfDay() method
LocalDateTime datetime = date.atStartOfDay();
System.out.println("date time : "+datetime);
}
}
Output:
date : 2020-08-20
date time : 2020-08-20T00:00
The LocalDate class provides one more overloaded method that takes ZoneId as argument. This method is similar to above method except that it requires an argument and returns a date with time based on specified zone.
public ZonedDateTime atStartOfDay​(ZoneId zone)
ZoneId represents a time zone like "Asia/Kolkata", "Europe/Paris", etc. See the example here.
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
/*
* Example of atStartOfDay(ZoneId) method of LocalDate class
*/
public class JExercise {
public static void main(String[] args) {
// Take a date
LocalDate date = LocalDate.parse("2020-08-20");
// Displaying date
System.out.println("date : "+date);
// Using atStartOfDay(ZoneId) method
ZonedDateTime datetime = date.atStartOfDay(ZoneId.of("Asia/Tokyo"));
System.out.println("date time : "+datetime);
}
}
Output:
date : 2020-08-20
date time : 2020-08-20T00:00+09:00[Asia/Tokyo]
Well, in this topic, we have learned to get a date with midnight time. We have used two methods atStartOfDay() and atStartOfDay(ZoneId) methods of LocalDate class.
If we missed something, you can suggest us at - info.javaexercise@gmail.com