Back to Java
2026-02-276 min read

Java Date

Learn Java Date step by step with clear examples and exercises.

Why This Matters

Java provides a comprehensive and flexible API for handling dates and times, making it easier to work with temporal data in your applications. This guide will walk you through the core concepts of Java's date and time functionality, along with practical examples, common mistakes, and frequently asked questions. Understanding these concepts is essential as they are used extensively in various application domains such as scheduling systems, e-commerce platforms, or data analysis tools.

Prerequisites

To fully understand this guide, you should be familiar with the following concepts:

  1. Basic understanding of Java programming language, including classes, objects, methods, and variables.
  2. Knowledge of object-oriented programming principles, such as encapsulation, inheritance, polymorphism, and abstraction.
  3. Familiarity with Java's syntax and data types, including primitive types (e.g., int, char), wrapper classes (e.g., Integer, Character), and basic control structures (e.g., loops, conditionals).
  4. Understanding of exception handling in Java using try-catch blocks.
  5. Basic understanding of the Java Standard Library, such as collections (e.g., ArrayList, HashMap) and I/O operations (e.g., reading from a file, writing to a console).

Core Concept

Java's date and time functionality is primarily based on three classes: java.util.Date, java.util.Calendar, and the modern java.time package, which was introduced in Java 8. In this guide, we will focus on the latter, as it offers a more intuitive and flexible API for handling dates and times.

The java.time package contains several classes that help manage temporal data, such as:

  1. LocalDate: Represents a date (year, month, day) without time-of-day or timezone information.
  2. LocalTime: Represents a time-of-day without date or timezone information.
  3. LocalDateTime: Combines both date and time-of-day in a single object.
  4. ZonedDateTime: Represents a date and time with a specific timezone.
  5. Instant: Represents a moment in time without any timezone or calendar system information.
  6. Duration: Represents a period of time, such as hours, minutes, seconds, etc.
  7. Period: Represents a period of time with a specific calendar system, like years, months, and days.
  8. DateTimeFormatter: Used to format dates and times according to desired patterns.
  9. ZoneId: Represents a timezone, such as "America/New_York" or "Europe/London".
  10. ZonedDateTimeUtils: Provides utility methods for working with ZonedDateTime.

Worked Example

Let's create a simple Java application that demonstrates how to work with dates and times using the java.time package.

import java.time.*;
import java.util.Scanner;

public class DateExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter year:");
int year = scanner.nextInt();

System.out.println("Enter month (1-12):");
int month = scanner.nextInt();

System.out.println("Enter day of the month (1-31):");
int day = scanner.nextInt();

LocalDate date = LocalDate.of(year, month, day);
System.out.printf("You entered: %s%n", date);

LocalTime time = LocalTime.now();
System.out.printf("Current time is: %s%n", time);

LocalDateTime localDateTime = LocalDateTime.of(date, time);
System.out.printf("Combined date and time: %s%n", localDateTime);

ZonedDateTime zdt = LocalDateTime.now().atZone(ZoneId.systemDefault());
System.out.printf("Current date and time (with timezone): %s%n", zdt);
}
}

In this example, we create a simple console application that asks the user to input a year, month, and day, and then creates a LocalDate object with those values. We also demonstrate how to get the current time using LocalTime.now(), combine date and time into a single LocalDateTime object, and obtain the current date and time with a specific timezone using ZonedDateTime.

Common Mistakes

  1. Not using the java.time package: Make sure to import the java.time package instead of the older java.util.Date class.
  2. Incorrect date formatting: When working with dates, ensure that you use the appropriate format strings for your specific needs. For example, when printing a LocalDateTime, use dd/MM/yyyy HH:mm:ss instead of MM/dd/yyyy hh:mm:ss a.
  3. Timezone issues: Be aware of timezone differences and make sure to handle them appropriately when working with ZonedDateTime or other classes that involve timezones.
  4. Not considering leap years: When working with dates, remember to account for leap years, as they have 29 days in February instead of the usual 28.
  5. Ignoring exceptions: Make sure to handle exceptions when working with date and time operations, such as DateTimeException, which can occur due to invalid input or out-of-range values.
  6. Misusing DateTimeFormatter: Be aware that DateTimeFormatter is thread-safe, so it should be reused instead of creating a new instance for each formatting operation.
  7. Confusing Duration and Period: Remember that Duration represents a period of time in seconds, minutes, hours, etc., while Period represents a period of time with a specific calendar system, like years, months, and days.

Practice Questions

  1. Write a Java program that prints the current date and time in the following format: dd/MM/yyyy HH:mm:ss.
  2. Create a Java application that calculates the number of days between two given dates using the LocalDate class.
  3. Given a ZonedDateTime, write a method that converts it to a LocalDateTime object.
  4. Write a Java program that prints the next 5 Mondays starting from today.
  5. Create a Java application that calculates the age of a person based on their birth date and the current date.
  6. Write a Java program that determines whether a given year is a leap year or not.
  7. Given two LocalDateTime objects, write a method that returns the duration between them in years, months, days, hours, minutes, and seconds.
  8. Write a Java program that converts a string representing a date (e.g., "2023-03-15") into a LocalDate object using DateTimeFormatter.
  9. Given a ZonedDateTime, write a method that converts it to a String in the format "yyyy-MM-dd'T'HH:mm:ss.SSSXXX".

FAQ

  1. Why should I use the java.time package instead of the older Date class? The java.time package offers a more flexible and intuitive API for handling dates and times, as well as improved performance and support for modern Java versions. It also addresses many issues present in the older Date and Calendar classes, such as inconsistent handling of timezones and date arithmetic.
  2. How do I format dates in Java using the java.time package? To format dates in Java, use the DateTimeFormatter class. For example, to print a date in the format dd/MM/yyyy, you can create a formatter like this: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");.
  3. How do I handle timezones in Java using the java.time package? To work with timezones, use the ZonedDateTime class. You can create a ZonedDateTime object by specifying a date and time along with a specific timezone ID. For example: ZonedDateTime zdt = ZonedDateTime.of(2023, 1, 1, 0, 0, 0, 0, ZoneId.of("America/New_York"));.
  4. How do I convert a LocalDateTime to a ZonedDateTime in Java? To convert a LocalDateTime to a ZonedDateTime, you can use the atZone method and specify a timezone ID: ZonedDateTime zdt = localDateTime.atZone(ZoneId.of("America/New_York"));.
  5. How do I compare two LocalDate objects in Java? To compare two LocalDate objects, use the compareTo() method. For example: LocalDate date1 = LocalDate.of(2023, 3, 15); LocalDate date2 = LocalDate.of(2023, 4, 1); int comparisonResult = date1.compareTo(date2);. The result will be negative if date1 is before date2, zero if they are equal, and positive if date1 is after date2.
  6. How do I get the first day of a month using LocalDate in Java? To get the first day of a month using LocalDate, you can use the withDayOfMonth() method with 1 as an argument: LocalDate firstDayOfMonth = date.withDayOfMonth(1);.
  7. How do I get the last day of a month using LocalDate in Java? To get the last day of a month using LocalDate, you can use the with() method and set the day to the maximum value for the specific month: LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());.
  8. How do I get the number of days in a month using LocalDate in Java? To get the number of days in a month using LocalDate, you can use the lengthOfMonth() method: int daysInMonth = date.lengthOfMonth();.
Java Date | Java | XQA Learn