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:


Advanced: Date Manipulation and Arithmetic

The java.time API makes it incredibly easy to perform date and time calculations. Because LocalDate and LocalDateTime objects are immutable, any arithmetic operation returns a new object rather than modifying the original one.

You can use methods like plusDays(), minusMonths(), plusHours(), etc.

Date Arithmetic

import java.time.LocalDate;

public class Main { public static void main(String[] args) { LocalDate today = LocalDate.now(); System.out.println("Today: " + today); // Add 1 week and 3 days LocalDate futureDate = today.plusWeeks(1).plusDays(3); System.out.println("Future Date: " + futureDate); // Subtract 2 months LocalDate pastDate = today.minusMonths(2); System.out.println("Past Date: " + pastDate); } }


Advanced: Comparing Dates and Calculating Periods

You often need to check if a date is before or after another date, or calculate the exact amount of time between two dates.

Comparing Dates and Periods

import java.time.LocalDate;
import java.time.Period;

public class Main { public static void main(String[] args) { LocalDate today = LocalDate.now(); LocalDate newYear = LocalDate.of(today.getYear() + 1, 1, 1); if (today.isBefore(newYear)) { System.out.println("New Year hasn't happened yet."); } // Calculate the difference between the two dates Period timeUntilNewYear = Period.between(today, newYear); System.out.println("Time until New Year: " + timeUntilNewYear.getMonths() + " months and " + timeUntilNewYear.getDays() + " days."); } }


Advanced: Parsing Dates from Strings

If you receive a date as a string (e.g., from a user input or an API), you can parse it into a java.time object using the parse() method. If the string is not in the standard ISO format (yyyy-MM-dd), you must provide a DateTimeFormatter to specify the pattern.

Parsing Dates

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main { public static void main(String[] args) { // Standard ISO format parses automatically LocalDate date1 = LocalDate.parse("2024-12-25"); System.out.println("Parsed ISO date: " + date1); // Custom format requires a DateTimeFormatter String customDateStr = "15/08/2024"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); LocalDate date2 = LocalDate.parse(customDateStr, formatter); System.out.println("Parsed Custom date: " + date2); } }


Exercise

?

Which modern Java class represents a date without time or time-zone?