In Java, the java.time
package provides a comprehensive set of classes for working with dates and times. This package was introduced in Java 8 and provides a much more powerful and flexible approach to working with dates and times than the previous java.util.Date
and java.util.Calendar
classes.
Here’s an example that shows how to work with dates and times using the java.time
package:
import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeExample { public static void main(String[] args) { // Create a LocalDate object representing today's date LocalDate today = LocalDate.now(); System.out.println("Today's date: " + today); // Create a LocalTime object representing the current time LocalTime currentTime = LocalTime.now(); System.out.println("Current time: " + currentTime); // Create a LocalDateTime object representing the current date and time LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("Current date and time: " + currentDateTime); // Format a date and time using a DateTimeFormatter object DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDateTime = currentDateTime.format(formatter); System.out.println("Formatted date and time: " + formattedDateTime); } }
In this example, we use the LocalDate
, LocalTime
, and LocalDateTime
classes to work with dates and times. We create objects representing today’s date, the current time, and the current date and time using the now()
method of each class.
We also use the DateTimeFormatter
class to format a date and time as a string. We create a DateTimeFormatter
object using the ofPattern()
method and a format string, and then use the format()
method of the LocalDateTime
object to format the date and time as a string.
The output of this example might look something like this:
Today's date: 2023-03-23 Current time: 10:30:45.273 Current date and time: 2023-03-23T10:30:45.273 Formatted date and time: 2023-03-23 10:30:45
The java.time
package provides many other useful classes and methods for working with dates and times, such as Period
, Duration
, and ZoneId
. It also provides support for parsing and formatting dates and times in various formats.