Date and Time API
The Date and Time API in Java 8 introduced a new set of classes for handling dates, times, and time zones. It provides a more comprehensive and intuitive way to work with dates and times compared to the older java.util.Date
and java.util.Calendar
classes.
Java 8 Date and Time Classes
The main classes in the Date and Time API include:
LocalDate
: Represents a date without time, such as2023-07-12
.LocalTime
: Represents a time without a date, such as14:30:45
.LocalDateTime
: Represents a date and time, such as2023-07-12T14:30:45
.ZonedDateTime
: Represents a date, time, and time zone.
These classes provide various methods for manipulating and formatting dates and times.
Example
Here's an example of how to use the Date and Time API:
TEXT/X-JAVA
1import java.time.LocalDate;
2import java.time.LocalTime;
3import java.time.LocalDateTime;
4
5public class Main {
6 public static void main(String[] args) {
7 LocalDate date = LocalDate.now();
8 LocalTime time = LocalTime.now();
9 LocalDateTime dateTime = LocalDateTime.now();
10
11 System.out.println("Current Date: " + date);
12 System.out.println("Current Time: " + time);
13 System.out.println("Current Date and Time: " + dateTime);
14 }
15}
This code snippet demonstrates how to get the current date, time, and date-time using the Date and Time API. The now()
method is used to obtain the current date, time, or date-time instance.
The output will vary every time you run the program, but it will be similar to:
SNIPPET
1Current Date: 2023-07-12
2Current Time: 14:30:45
3Current Date and Time: 2023-07-12T14:30:45
xxxxxxxxxx
15
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();
System.out.println("Current Date: " + date);
System.out.println("Current Time: " + time);
System.out.println("Current Date and Time: " + dateTime);
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment