Date Time Functions in Java Tutorial
Chapter 14 · Java Programming Series
PBA Institute 12 min read Intermediate 2024

Date & Time Functions in Java

Working with dates and times is a daily requirement — logging events, calculating ages, generating invoices. Java 8 introduced the powerful java.time package with classes like LocalDate, LocalTime, LocalDateTime and Duration that are immutable, thread-safe and easy to use.

Key Features

📅

LocalDate

Date without time or timezone (yyyy-MM-dd).

LocalTime

Time without date (HH:mm:ss).

🗓️

LocalDateTime

Combined date and time.

🌍

ZonedDateTime

Date-time with a timezone.

📐

Formatter

Convert between String and date types.

⏱️

Duration / Period

Arithmetic between two date/time values.

Syntax

  • Import: import java.time.*;
  • Now: LocalDateTime.now()
  • Create date: LocalDate.of(2024, 5, 15)
  • Format: DateTimeFormatter.ofPattern("dd-MM-yyyy")

Key java.time Classes

ClassPurposeExampleOutput
LocalDateDate onlyLocalDate.now()2024-05-15
LocalTimeTime onlyLocalTime.now()10:45:32
LocalDateTimeBothLocalDateTime.now()2024-05-15T10:45
PeriodDate diffPeriod.between(a, b)P2Y3M
DurationTime diffDuration.between(t1, t2)PT2H30M

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind Date Time Functions in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Current Date & Time
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;

class Main
{
    public static void main(String args[])
    {
        LocalDate     date  = LocalDate.now();
        LocalTime     time  = LocalTime.now();
        LocalDateTime dt    = LocalDateTime.now();

        System.out.println("Date: " + date);
        System.out.println("Time: " + time);
        System.out.println("Both: " + dt);
    }
}
Output Date: 2024-05-15
Time: 10:45:32.123
Both: 2024-05-15T10:45:32.123

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Custom Format
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class Main
{
    public static void main(String args[])
    {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");

        System.out.println(now.format(fmt));
    }
}
Output 15-05-2024 10:45
Parse a String
import java.time.LocalDate;

class Main
{
    public static void main(String args[])
    {
        LocalDate d = LocalDate.parse("2024-08-25");

        System.out.println("Year: " + d.getYear());
        System.out.println("Month: " + d.getMonth());
        System.out.println("Day: " + d.getDayOfMonth());
    }
}
Output Year: 2024
Month: AUGUST
Day: 25
Date Arithmetic
import java.time.LocalDate;

class Main
{
    public static void main(String args[])
    {
        LocalDate today = LocalDate.now();
        LocalDate later = today.plusDays(15);
        LocalDate before = today.minusMonths(2);

        System.out.println(today);
        System.out.println(later);
        System.out.println(before);
    }
}
Output Prints today, today+15 days, today−2 months
Age Calculation with Period
import java.time.*;

class Main
{
    public static void main(String args[])
    {
        LocalDate dob = LocalDate.of(2000, 1, 15);
        LocalDate today = LocalDate.now();

        Period age = Period.between(dob, today);

        System.out.println("Age = " + age.getYears() + " years");
    }
}
Output Age = 24 years
Duration Between Times
import java.time.*;

class Main
{
    public static void main(String args[])
    {
        LocalTime t1 = LocalTime.of(9, 0);
        LocalTime t2 = LocalTime.of(11, 30);

        Duration d = Duration.between(t1, t2);

        System.out.println("Minutes = " + d.toMinutes());
    }
}
Output Minutes = 150

Notes & Tips

  • Prefer java.time over the old java.util.Date / Calendar.
  • All java.time classes are immutable — methods return new instances.
  • Use DateTimeFormatter for both formatting and parsing.
  • Period measures dates; Duration measures time amounts.
  • Always specify a timezone for global apps — use ZonedDateTime.

Real-World Use Cases

Invoices

Generate due dates, payment dates and overdue periods.

Scheduling

Calendar apps, reminders and recurring events.

Logging

Timestamp every event with ISO 8601 format.

Global Apps

Handle multiple time zones cleanly with ZonedDateTime.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Print today's date in dd/MM/yyyy format.
  • Q2. Calculate your age in years and days from your DOB.
  • Q3. Determine if a year is a leap year using LocalDate.isLeapYear().
  • Q4. Find the day of the week for any date.
  • Q5. Compute how many days between two dates.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Difference between java.util.Date and java.time.LocalDateTime?
Old Date is mutable and not thread-safe; LocalDateTime is immutable, clear and modern.
Q2 How do you format a LocalDate?
Use DateTimeFormatter.ofPattern("dd-MM-yyyy") and call date.format(fmt).
Q3 Difference between Period and Duration?
Period uses date-based units (years, months, days); Duration uses time-based units (hours, minutes, seconds).
Q4 Is LocalDateTime timezone aware?
No — use ZonedDateTime or OffsetDateTime for timezone information.
Q5 How to convert String to LocalDate?
LocalDate.parse("2024-05-15") or with a custom formatter.

FAQ

FAQ 1 Should I still use java.util.Date?
Avoid it in new code — use java.time which is safer and easier.
FAQ 2 Is LocalDate thread-safe?
Yes, all java.time classes are immutable and thread-safe.
FAQ 3 How do I get current Unix timestamp?
Instant.now().getEpochSecond() or System.currentTimeMillis().
FAQ 4 How do I add 3 hours to a time?
time.plusHours(3) — returns a new LocalTime.
FAQ 5 Does LocalDate have a timezone?
No — that's why it's called Local. Use ZonedDateTime when timezone matters.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Date Time Functions in Java:

  • Forgetting the semicolon ; at the end of statements while using Date Time Functions.
  • Mixing up similar method names — read Java docs before using new APIs related to Date Time Functions.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Method Overriding Collections Framework OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving Date Time Functions — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
Date Time FunctionsDate Time Functions conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Method Overriding — strengthens your understanding of the previous building block.
NEXT Collections Framework — the natural progression after mastering Date Time Functions.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Java's java.time API provides clean, immutable classes for dates and times. Use LocalDate, LocalTime, LocalDateTime, plus Period/Duration for arithmetic and DateTimeFormatter for parsing & formatting. Prefer it over the legacy java.util.Date.

Continue Learning