Preface
In Java development, handling dates and times is a common task. Especially when processing data, it is very important to obtain the start and end times of a specific date. This blog will explain how to use JavaLocalDate
andLocalDateTime
Class to get the start time (00:00:00) and end time (23:59:59) of a certain day.
1. Java Date Time API Overview
Java 8 introduces a new datetime API (package) to better handle dates and times. Compared to the old one
and
Class, new API is easier to use and thread safe. We will use the following two classes:
- LocalDate: Indicates a date (year, month, and date) without time zone.
- LocalDateTime: Indicates a date (year, month, day, hour, minute, and second) without a time zone.
2. Get the start and end time of the day
We will write a simple Java program to get the start and end times of the specified date. Here is a code example:
import ; import ; import ; import ; public class DateExample { public static void main(String[] args) { // Specify date LocalDate date = (2024, 10, 24); // Get the start time of the day LocalDateTime startOfDay = (); // Get the end time of the day LocalDateTime endOfDay = (); // 23:59:59.999999999 // Format output DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss"); ("Start time: " + (formatter)); ("End time: " + (formatter)); } }
Code parsing
Specified date:use
(2024, 10, 24)
A date object representing October 24, 2024 was created.Get the start time: Called
atStartOfDay()
Method, return the start time of the date (i.e. 00:00:00).Get the end time: Called
atTime()
Get the end time of the day, which represents 23:59:59.9999999999. You can use it as needed(23, 59, 59)
To get the simple 23:59:59 format.Format output:use
DateTimeFormatter
Format date and time into strings for easy printing output.
Running results
After running the above code, you will see the following output:
Start time: 2024-10-24 00:00:00
End time: 2024-10-24 23:59:59
3. Summary
This article describes how to use Java 8's new datetime API to get the start and end times of a specified date. useLocalDate
andLocalDateTime
Classes, developers can handle dates and times more easily, avoiding many troubles caused by old APIs.
In this way, you can accurately handle date-related requirements in actual development, whether in database queries, data statistics or time-frame comparisons, which are very useful tips.
This is the article about how to use Java to obtain the start and end time of the day. For more related content on Java to obtain the start and end time of the day, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!