The atTime()
method belongs to the LocalDate
class in the Java Date-Time API, not the Date
class. This method combines this date with a time to create a LocalDateTime
.
Here’s an example:
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class AtTimeExample {
public static void main(String[] args) {
// Create a LocalDate instance
LocalDate date = LocalDate.of(2023, 1, 23);
// Create a LocalTime instance
// 24-hour clocks
LocalTime time = LocalTime.of(13, 45);
// Use atTime() to combine date and time into a LocalDateTime
LocalDateTime dateTime = date.atTime(time);
System.out.println(dateTime);
}
}
Output:
2023-01-23T13:45
In this example, a LocalDate
and a LocalTime
are combined into a LocalDateTime
using the atTime()
method.
The LocalDate
class also has an overloaded atTime
method that takes the hour and minute directly, instead of a LocalTime
instance.
Here’s an example where we set 14 hours and 30 minutes directly.
package org.kodejava.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class AtTimeOtherExample {
public static void main(String[] args) {
// Create a LocalDate instance
LocalDate date = LocalDate.of(2023, 1, 23);
// Use atTime() to combine date and hour and minute into a
// LocalDateTime
LocalDateTime dateTime = date.atTime(14, 30);
System.out.println(dateTime);
}
}
Output:
2023-01-23T14:30
In this example, 14:30
(in 24-hour clock) is directly passed into atTime
. There is another version of atTime()
that takes hrs
, min
, and sec
. That would look like this:
// include seconds
LocalDateTime dateTime = date.atTime(14, 30, 20);
// include nano seconds
LocalDateTime dateTime = date.atTime(14, 30, 20, 200);
These are all the overloaded versions of atTime()
in LocalDate
.
Remember, LocalDate
, LocalTime
, LocalDateTime
and others from Java Date-Time API are designed to replace the old Date
and Calendar
classes from java.util
package. They are more consistent, easier to understand and use.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024