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
| Class | Purpose | Example | Output |
|---|---|---|---|
| LocalDate | Date only | LocalDate.now() | 2024-05-15 |
| LocalTime | Time only | LocalTime.now() | 10:45:32 |
| LocalDateTime | Both | LocalDateTime.now() | 2024-05-15T10:45 |
| Period | Date diff | Period.between(a, b) | P2Y3M |
| Duration | Time diff | Duration.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.
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);
}
}
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.
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));
}
}
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());
}
}
Month: AUGUST
Day: 25
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);
}
}
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");
}
}
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());
}
}
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.
Old Date is mutable and not thread-safe; LocalDateTime is immutable, clear and modern.
Use
DateTimeFormatter.ofPattern("dd-MM-yyyy") and call date.format(fmt).
Period uses date-based units (years, months, days); Duration uses time-based units (hours, minutes, seconds).
No — use ZonedDateTime or OffsetDateTime for timezone information.
LocalDate.parse("2024-05-15") or with a custom formatter.
FAQ
Avoid it in new code — use java.time which is safer and easier.
Yes, all java.time classes are immutable and thread-safe.
Instant.now().getEpochSecond() or System.currentTimeMillis().
time.plusHours(3) — returns a new LocalTime.
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
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
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Date Time Functions | Date Time Functions concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
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.