Page Content

Tutorials

What is the Date-Time API in Java? With Code Example

Date-Time API in Java

Over the years, Java has developed a vast array of classes for handling dates and timings. Classes like Date, Calendar, and GregorianCalendar were initially used by developers. Nevertheless, a brand-new Date-Time API was added to the java.time package with Java SE 8, providing more transparent, reliable, and unchangeable options. While java.time should typically be preferred in new code, working with older applications requires an awareness of the heritage classes.

Legacy Date and Time API

The java.util.Date Class

The Date class, which may be found in the java.util package, was Java’s first method of encapsulating the current time and date. For milliseconds since the epoch, it basically depicts a single point in time.

  • Constructors:
    • Date(): Initialises the object with the current date and time.
    • Date(long millisec): Creates a Date object from the specified number of milliseconds since the epoch.
  • Key Methods: While many original Date methods (like getYear()getMonth()) were deprecated with Java 1.1 (and their functionality moved to Calendar and DateFormat), some non-deprecated methods remain useful. These include getTime() (returns milliseconds since epoch), setTime(long time)after(Date date)before(Date date)equals(Object date)compareTo(Date date), and toString().

Here’s a quick example:

import java.util.Date;
public class DateDemo {
    public static void main(String[] args) {
        // Instantiate a Date object for the current time
        Date currentDate = new Date();
        System.out.println("Current Date and Time: " + currentDate.toString()); 
        // Get milliseconds since epoch
        long milliseconds = currentDate.getTime(); 
        System.out.println("Milliseconds since Jan 1, 1970 GMT: " + milliseconds);
        // Create a specific date (using milliseconds since epoch for simplicity)
        Date pastDate = new Date(123456789000L); 
        System.out.println("Past Date: " + pastDate);
        // Compare dates
        System.out.println("Is current date after past date? " + currentDate.after(pastDate)); 
    }
}

Output:

Current Date and Time: Sat Aug 23 11:52:33 GMT 2025
Milliseconds since Jan 1, 1970 GMT: 1755949953692
Past Date: Thu Nov 29 21:33:09 GMT 1973
Is current date after past date? true

Calendar and GregorianCalendar classes in Java.util.

Second, java.util and java.util.Calendar.Calendar Classes in Gregorian A method to convert between a set of calendar fields, including year, month, day, hour, minute, and second, and a single point in time, expressed in milliseconds since the epoch, is provided by the Calendar class, an abstract class.  Because Calendar is abstract, you cannot instantiate it directly. Instead, you use concrete subclasses like GregorianCalendar.

  • getInstance(): For the static Calendar, use getInstance().The GregorianCalendar object that is normally returned by the getInstance() method is initialised with the current date and time in the default locale and time zone.
  • Calendar Fields: Calendar fields are accessed using constants like Calendar.YEARCalendar.MONTHCalendar.DAY_OF_MONTH, etc.. A crucial point is that months are zero-based (Calendar.JANUARY is 0).
  • Methodsget(int field) retrieves a field’s value, set(int field, int value) modifies a field, and add(int field, int amount) adds or subtracts time. getTimeInMillis() returns the time in milliseconds, and setTimeInMillis(long millis) sets it.
  • GregorianCalendar: The common concrete implementation of the Gregorian calendar is called GregorianCalendar. It gives constructors the ability to specify precise times and dates, such as GregorianCalendar(int year, int month, int dayOfMonth). Additionally, the isLeapYear (int year) method is included.

Here’s an example:

import java.util.Calendar;
import java.util.GregorianCalendar;
public class CalendarDemo {
    public static void main(String[] args) {
        // Create a GregorianCalendar instance, typically for the current time
        GregorianCalendar gcalendar = new GregorianCalendar(); 
        // Display current date and time information
        System.out.print("Date: " + (gcalendar.get(Calendar.MONTH) + 1)); // Month is 0-indexed 
        System.out.print(" " + gcalendar.get(Calendar.DAY_OF_MONTH)); 
        System.out.println(" " + gcalendar.get(Calendar.YEAR)); 
        System.out.print("Time: " + gcalendar.get(Calendar.HOUR));
        System.out.print(":" + gcalendar.get(Calendar.MINUTE));
        System.out.println(":" + gcalendar.get(Calendar.SECOND));
        // Check if the current year is a leap year
        if (gcalendar.isLeapYear(gcalendar.get(Calendar.YEAR))) { 
            System.out.println("The current year is a leap year.");
        } else {
            System.out.println("The current year is not a leap year.");
        }
    }
}

Output:

Date: 8 23 2025
Time: 11:19:57
The current year is not a leap year.

New Date-Time API () (JDK 8+)

With its introduction in Java SE 8, the java.time package offers a contemporary, extensible, and immutable API. It fixes a number of the legacy API’s issues, including mutability and unclear time zone definitions.

LocalDate

Date of Localisation LocalDate is a date that does not have a time zone or time. When all you have to store is a date on the calendar (like a birthday), it’s perfect.

  1. Creation: LocalDate.now() for the current date, LocalDate.of(year, month, day) for a specific date, or LocalDate.parse("YYYY-MM-DD") from a string.
  2. Manipulation: Methods like plusDays(long days), minusYears(long years), withMonth(int month) return new LocalDate instances due to its immutability.
  3. Comparison: isBefore(LocalDate other), isAfter(LocalDate other), isEqual(LocalDate other).
import java.time.LocalDate;
public class LocalDateDemo {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now(); // Current date 
        System.out.println("Today's date: " + today);
        LocalDate independenceDay = LocalDate.of(1901, 1, 1); // Specific date 
        System.out.println("Independence Day: " + independenceDay);
        LocalDate parsedDate = LocalDate.parse("2023-10-27"); // Parse from string 
        System.out.println("Parsed date: " + parsedDate);
        LocalDate tomorrow = today.plusDays(1); // Adding days (returns new instance) 
        System.out.println("Tomorrow's date: " + tomorrow);
        System.out.println("Is today before Independence Day? " + today.isBefore(independenceDay)); 
    }
}

Output:

Today's date: 2025-08-23
Independence Day: 1901-01-01
Parsed date: 2023-10-27
Tomorrow's date: 2025-08-24
Is today before Independence Day? false

LocalTime

LocalTime is a time of day that does not include a date or time zone. It’s helpful for times when the clock is on the wall.

  • Creation: LocalTime.now() for the current time, LocalTime.of(hour, minute, second) for a specific time, LocalTime.parse("HH:MM:SS") from a string.
  • Manipulation: Similar to LocalDate, methods like plusHours(long hours) or minusMinutes(long minutes) return new LocalTime objects.
import java.time.LocalTime;
public class LocalTimeDemo {
    public static void main(String[] args) {
        LocalTime now = LocalTime.now(); // Current time 
        System.out.println("Current time: " + now);
        LocalTime meetingTime = LocalTime.of(14, 30, 0); // 2:30 PM 
        System.out.println("Meeting time: " + meetingTime);
        LocalTime later = now.plusHours(2); // Add 2 hours 
        System.out.println("Time in 2 hours: " + later);
        System.out.println("Meeting is after current time? " + meetingTime.isAfter(now)); 
    }
}

Output:

Current time: 11:09:52.969744846
Meeting time: 14:30
Time in 2 hours: 13:09:52.969744846
Meeting is after current time? true

LocalDateTime

LocalDateTime combines LocalDate and LocalTime to represent a date and time without any time-zone information. When discussing dates and times in a localised context, where the particular time zone is irrelevant or has been addressed individually, it is frequently utilised.

  1. Creation: LocalDateTime.now(), LocalDateTime.of(year, month, day, hour, minute), or LocalDateTime.parse("YYYY-MM-DDTHH:MM:SS").
  2. Manipulation: It provides a full set of plus, minus, and with methods, similar to LocalDate and LocalTime.
import java.time.LocalDateTime;
public class LocalDateTimeDemo {
    public static void main(String[] args) {
        LocalDateTime currentDateTime = LocalDateTime.now(); // Current date and time 
        System.out.println("Current Date and Time: " + currentDateTime);
        LocalDateTime eventDateTime = LocalDateTime.of(2025, 6, 15, 18, 0); 
        System.out.println("Event Date and Time: " + eventDateTime);
        LocalDateTime futureDateTime = currentDateTime.plusWeeks(1).plusHours(3);
        System.out.println("Future Date and Time: " + futureDateTime);
    }
}

Output:

Current Date and Time: 2025-08-23T11:05:38.901199008
Event Date and Time: 2025-06-15T18:00
Future Date and Time: 2025-08-30T14:05:38.901199008

Other Key Classes in java.time (Briefly)

  • Instant: Denotes a moment in time, frequently regarded as a timestamp. It’s helpful for storing event times in a format that machines can understand.
  • ZonedDateTime: ZonedDateTime is a LocalDateTime that has time-zone information, which is essential for managing time zones and various geographic locations.
  • OffsetDateTime: A LocalDateTime that is offset from Greenwich/UTC but does not adhere to all time zone regulations.
  • DateTimeFormatter: For formatting java.time objects into strings and parsing strings into java.time objects, use the DateTimeFormatter function.

In conclusion,

For new Java development, the java.time API in JDK 8+ is the best option because of its excellent design principles: immutability (operations return new objects, which makes them intrinsically thread-safe and easier to reason about), clarity (types like LocalDate clearly define their purpose), and a fluent API that improves readability and chaining of operations. Although the outdated Date and Calendar classes are still available for backward compatibility, it is generally discouraged to utilise them in new projects.

Index