Java has had several date and time libraries over the years, but since Java 8, the modern and recommended way to handle dates and times is with the java.time package.
This package is based on the Joda-Time library and provides a much more intuitive and comprehensive API than the old java.util.Date and java.util.Calendar classes.
java.timeThe java.time package includes many classes, but here are some of the most important ones:
LocalDate: Represents a date (year, month, day) without time or time-zone.LocalTime: Represents a time (hour, minute, second) without a date or time-zone.LocalDateTime: Represents a date and time, but still without a time-zone.ZonedDateTime: Represents a date and time with a specific time-zone.DateTimeFormatter: A formatter for displaying and parsing date-time objects.To get the current date and time, you can use the now() method on the appropriate class.
import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime;public class Main { public static void main(String[] args) { LocalDate myDate = LocalDate.now(); // Get current date System.out.println("Current Date: " + myDate); LocalTime myTime = LocalTime.now(); // Get current time System.out.println("Current Time: " + myTime); LocalDateTime myDateTime = LocalDateTime.now(); // Get current date and time System.out.println("Current Date and Time: " + myDateTime); } }
The default output of the date-time objects is not always user-friendly. The DateTimeFormatter class is used to format or parse date-time objects.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter;public class Main { public static void main(String[] args) { LocalDateTime myDateTime = LocalDateTime.now(); System.out.println("Before formatting: " + myDateTime); // Create a formatter with a specific pattern DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); String formattedDate = myDateTime.format(myFormatObj); System.out.println("After formatting: " + formattedDate); } }
You can use many different patterns with ofPattern() to get the exact format you need. Some common pattern letters are:
yyyy - YearMM - Monthdd - DayHH - Hour (00-23)mm - Minutess - SecondE - Day name (e.g., "Tue")