Java Date and Time
Java Date and Time
TIME
Java Dates
Java does not have a built-in Date class, but we can import the java.time package to work with the date
and time API. The package includes many date and time classes
Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))
LocalTime Represents a time (hour, minute, second and nanoseconds
(HH-mm-ss-ns))
LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-
ss-ns)
DateTimeFormatt Formatter for displaying and parsing date-time objects
er
Display Current Date
To display the current date, import the java.time.LocalDate class, and use its now() method:
To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class,
and use its now() method:
To display the current date and time, import the java.time.LocalDateTime class, and use its now()
method:
The "T" in the example above is used to separate the date from the time. You can use the DateTimeFormatter
class with the ofPattern() method in the same package to format or parse date-time objects. The following
example will remove both the "T" and nanoseconds from the date-time:
import java.time.LocalDateTime; // Import the LocalDateTime class
import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class