PUBLISHED ON: JANUARY 19, 2021
Java LocalDate atStartOfDay() Method with Time Zone
Java atStartOfDay(ZoneId)
method is used to combine start time (midnight time) with the specified date based on the time-zone. This method returns zoned date-time rather than local date-time.
It returns a zoned date-time from this date at the earliest valid time according to the rules in the time-zone. The syntax of the method is given below.
Syntax
public ZonedDateTime atStartOfDay(ZoneId zone)
Parameters
It takes a single parameter as a zone id.
Returns:
It returns a zoned based date-time from this date at the earliest valid time.
Example 1:
Lets get the midnight time of a date based on the specified time zone. Here we pass the time zone id to the atStartOfDay()
method and get zoned date time. We can either specify the zone or let it on the system to detect automatically.
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo {
public static void main(String[] args){
// Getting a date
LocalDate localDate = LocalDate.of(2018, Month.JANUARY, 18);
// Displaying date
System.out.println("Date: \n"+localDate);
// Getting start time of the date
ZonedDateTime localDateTime = localDate.atStartOfDay(ZoneId.of("Asia/Kolkata"));
// Displaying date and time of start of the date
System.out.println("Date with start time: \n"+localDateTime);
}
}
Date:
2018-01-18
Date with start time:
2018-01-18T00:00+05:30[Asia/Kolkata]
Example 2:
If we don't want to specify the time zone manually then use systemDefault()
method to set the default zone. In this example, we are using system default zone id and getting the local date-time
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Demo {
public static void main(String[] args){
// Getting a date
LocalDate localDate = LocalDate.of(2018, Month.JANUARY, 18);
// Displaying date
System.out.println("Date: \n"+localDate);
// Getting start time of the date
ZonedDateTime localDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
// Displaying date and time of start of the date
System.out.println("Date with start time: \n"+localDateTime);
}
}
Date:
2018-01-18
Date with start time:
2018-01-18T00:00+05:30[Asia/Kolkata]
Live Example:
Here, we are with a live java example. You can execute it for the desired result and test your code.