Java Date and Time

Java Date and Time

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.


Key Classes in java.time

The java.time package includes many classes, but here are some of the most important ones:


Displaying the Current Date and Time

To get the current date and time, you can use the now() method on the appropriate class.

Current Date and Time

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); } }


Formatting Date and Time

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.

Formatting Example

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: