0% found this document useful (0 votes)
2 views18 pages

Java DateTime API

The document provides a comprehensive guide to the Java Date & Time API introduced in Java 8, specifically the java.time package, which offers immutable and thread-safe classes for handling dates and times. It covers various classes such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, Duration, and Period, along with their creation, manipulation, and formatting. Additionally, it includes practical examples for age calculation, finding the next business day, and scheduling meetings across multiple time zones.

Uploaded by

somanikartik12
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

Java DateTime API

The document provides a comprehensive guide to the Java Date & Time API introduced in Java 8, specifically the java.time package, which offers immutable and thread-safe classes for handling dates and times. It covers various classes such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant, Duration, and Period, along with their creation, manipulation, and formatting. Additionally, it includes practical examples for age calculation, finding the next business day, and scheduling meetings across multiple time zones.

Uploaded by

somanikartik12
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java

Date & Time API


Complete Reference Guide

[Link] package · Java 8+


LocalDate · LocalTime · LocalDateTime · ZonedDateTime · Instant · Duration · Period ·
DateTimeFormatter
1. Introduction
Java 8 introduced the [Link] package — a complete, immutable, thread-safe replacement for the
legacy [Link] and [Link] classes. Designed by the author of Joda-Time, it fixes
long-standing issues such as mutable state, confusing 0-based months, and poor timezone support.

Old API vs New API


// Old (avoid)
Date date = new Date();
Calendar cal = [Link]();
[Link](2024, 0, 15); // 0 = January — confusing!

// New (Java 8+)


LocalDate date = [Link](2024, 1, 15); // 1 = January

Core Design Principles


• Immutable — every method returns a new object; originals are never modified.
• Fluent API — methods can be chained naturally.
• Clear naming — of(), now(), parse(), plus*(), minus*(), with*().
• Separation of concerns — date, time, and timezone are separate classes.
• ISO-8601 — default format follows international standard.

Page 2
2. Class Overview
Class Stores Example

LocalDate Date only (no time) 2024-01-15

LocalTime Time only (no date) 10:30:45.123

LocalDateTime Date + Time (no zone) 2024-01-15T10:30:45

ZonedDateTime Date + Time + Timezone 2024-01-15T10:30:45+05:30[Asia/Kolkata]

OffsetDateTime Date + Time + UTC offset 2024-01-15T10:30:45+05:30

Instant Machine timestamp (epoch) 2024-01-15T05:00:45Z

Duration Time-based amount PT2H30M (2 hrs 30 min)

Period Date-based amount P1Y2M3D (1yr 2mo 3d)

ZoneId Timezone identifier Asia/Kolkata, Europe/London

DateTimeFormatter Format / parse patterns dd/MM/yyyy HH:mm

Page 3
3. LocalDate
Represents a date without time or timezone. Ideal for birthdays, deadlines, and calendar dates.

Creating
LocalDate today = [Link]();
LocalDate specific = [Link](2024, 1, 15);
LocalDate specific = [Link](2024, [Link], 15);
LocalDate parsed = [Link]("2024-01-15");
LocalDate fromEpoch = [Link](19737);

Accessing Fields
LocalDate d = [Link](2024, 6, 15);
[Link]() // 2024
[Link]() // JUNE
[Link]() // 6
[Link]() // 15
[Link]() // SATURDAY
[Link]() // 167
[Link]() // true
[Link]() // 30
[Link]() // 366

Manipulating (returns new object)


[Link](10) // 2024-06-25
[Link](2) // 2024-06-29
[Link](3) // 2024-09-15
[Link](1) // 2025-06-15
[Link](5) // 2024-06-10
[Link](1) // 2024-06-01 (first day of month)
[Link](1) // 2024-01-15
[Link](2025) // 2025-06-15

Comparing
LocalDate d1 = [Link](2024, 1, 15);
LocalDate d2 = [Link](2024, 6, 20);
[Link](d2) // true
[Link](d2) // false
[Link](d2) // false
[Link](d2) // negative number

Page 4
4. LocalTime
Represents time without a date or timezone. Used for business hours, schedules, and durations within a
day.

Creating
LocalTime now = [Link]();
LocalTime specific = [Link](10, 30); // 10:30:00
LocalTime specific = [Link](10, 30, 45); // 10:30:45
LocalTime specific = [Link](10, 30, 45, 100); // with nanoseconds
LocalTime parsed = [Link]("10:30:45");
LocalTime noon = [Link]; // 12:00
LocalTime midnight = [Link]; // 00:00

Accessing & Manipulating


LocalTime t = [Link](10, 30, 45);
[Link]() // 10
[Link]() // 30
[Link]() // 45
[Link]() // 0

[Link](2) // 12:30:45
[Link](30) // 11:00:45
[Link](10) // 10:30:35
[Link](9) // 09:30:45
[Link]([Link]) // true

Page 5
5. LocalDateTime
Combines date and time without timezone. Best for logging, scheduling, and timestamps where timezone
is not a concern.

Creating
LocalDateTime now = [Link]();
LocalDateTime specific = [Link](2024, 1, 15, 10, 30);
LocalDateTime combined = [Link](
[Link](2024, 1, 15),
[Link](10, 30)
);
LocalDateTime parsed = [Link]("2024-01-15T10:30:45");

Splitting & Converting


LocalDateTime dt = [Link]();
LocalDate date = [Link](); // extract date part
LocalTime time = [Link](); // extract time part

// add timezone to get ZonedDateTime


ZonedDateTime zdt = [Link]([Link]("Asia/Kolkata"));

Chaining Operations
LocalDateTime dt = [Link](2024, 1, 15, 10, 30);
[Link](1)
.plusHours(2)
.minusMinutes(30)
.withSecond(0); // 2024-01-16T12:00:00

Page 6
6. ZonedDateTime
A full date-time with timezone. Use for global applications, meeting schedulers, and any time zone
conversion is required.

Creating
ZonedDateTime now = [Link]();
ZoneId kolkata = [Link]("Asia/Kolkata");
ZonedDateTime zdt = [Link](
[Link](), kolkata
);

// from Instant
ZonedDateTime fromInstant = [Link]().atZone(kolkata);

Converting Between Timezones


ZonedDateTime kolkataTime = [Link]([Link]("Asia/Kolkata"));

// convert to other zones — same instant, different representation


ZonedDateTime londonTime = kolkataTime
.withZoneSameInstant([Link]("Europe/London"));
ZonedDateTime nyTime = kolkataTime
.withZoneSameInstant([Link]("America/New_York"));

// list all available zone IDs


[Link]()
.stream()
.sorted()
.forEach([Link]::println);

Common Zone IDs

Zone ID Region

Asia/Kolkata India (IST, +05:30)

Asia/Tokyo Japan (JST, +09:00)

Europe/London UK (GMT/BST)

Europe/Paris France (CET/CEST)

America/New_York US Eastern (EST/EDT)

America/Los_Angeles US Pacific (PST/PDT)

UTC Coordinated Universal Time

Page 7
7. Instant
Represents a point on the timeline in UTC — nanosecond precision since the Unix epoch (Jan 1, 1970).
Use for machine-readable timestamps, event logs, and database storage.
Instant now = [Link](); // current UTC moment
long epoch = [Link](); // seconds since 1970-01-01
long millis = [Link](); // milliseconds since 1970-01-01

// create from epoch


Instant fromEpoch = [Link](1705312200);
Instant fromMilli = [Link](1705312200000L);

// convert to ZonedDateTime for human-readable output


ZonedDateTime zdt = [Link]([Link]("Asia/Kolkata"));

// compare instants
Instant i1 = [Link]();
Instant i2 = [Link]().plusSeconds(60);
[Link](i2) // true
[Link](i2) // false

Page 8
8. Duration
Measures a time-based amount — hours, minutes, seconds, nanoseconds. Used to calculate elapsed time
between two time points.

Creating
Duration twoHours = [Link](2);
Duration thirtyMins = [Link](30);
Duration tenSeconds = [Link](10);
Duration fromISO = [Link]("PT2H30M"); // 2 hours 30 minutes

Between Two Times


LocalTime start = [Link](9, 0);
LocalTime end = [Link](17, 30);

Duration work = [Link](start, end);


[Link]() // 8
[Link]() // 510
[Link]() // 30600
[Link]() // 30 (Java 9 — remainder minutes)

// works with Instant too


Duration elapsed = [Link]([Link](), [Link]().plusSeconds(120));

Page 9
9. Period
Measures a date-based amount — years, months, days. Used to calculate age, subscription durations, or
calendar intervals.

Creating
Period oneYear = [Link](1);
Period twoMonths = [Link](2);
Period tenDays = [Link](10);
Period combined = [Link](1, 6, 15); // 1yr, 6mo, 15d
Period fromISO = [Link]("P1Y6M15D");

Between Two Dates — Age Calculator


LocalDate dob = [Link](2000, 5, 15);
LocalDate today = [Link]();

Period age = [Link](dob, today);


[Link]() // e.g. 24
[Link]() // months since last birthday
[Link]() // days since last month anniversary

[Link]("Age: %d years, %d months, %d days%n",


[Link](), [Link](), [Link]());

Duration vs Period

Duration Period

Measures Time (hours/minutes/seconds) Dates (years/months/days)

Used with LocalTime, Instant LocalDate

ISO example PT2H30M P1Y6M15D

DST aware No Yes

Page 10
10. DateTimeFormatter
Used to format date/time objects into strings and parse strings back into date/time objects.

Predefined Formatters
LocalDateTime now = [Link]();
[Link](DateTimeFormatter.ISO_DATE) // "2024-01-15"
[Link](DateTimeFormatter.ISO_TIME) // "10:30:45"
[Link](DateTimeFormatter.ISO_DATE_TIME) // "2024-01-15T10:30:45"
[Link](DateTimeFormatter.ISO_LOCAL_DATE_TIME)// "2024-01-15T10:30:45"
[Link](DateTimeFormatter.BASIC_ISO_DATE) // "20240115"

Custom Patterns
DateTimeFormatter f1 = [Link]("dd/MM/yyyy");
DateTimeFormatter f2 = [Link]("dd MMM yyyy");
DateTimeFormatter f3 = [Link]("dd/MM/yyyy HH:mm");
DateTimeFormatter f4 = [Link]("hh:mm a");
DateTimeFormatter f5 = [Link]("EEEE, dd MMMM yyyy");

LocalDateTime dt = [Link](2024, 1, 15, 10, 30);


[Link](f1) // "15/01/2024"
[Link](f2) // "15 Jan 2024"
[Link](f3) // "15/01/2024 10:30"
[Link](f4) // "10:30 AM"
[Link](f5) // "Monday, 15 January 2024"

Parsing Strings
DateTimeFormatter fmt = [Link]("dd/MM/yyyy");

LocalDate d = [Link]("15/01/2024", fmt);


LocalTime t = [Link]("10:30",
[Link]("HH:mm"));
LocalDateTime dt = [Link]("15/01/2024 10:30",
[Link]("dd/MM/yyyy HH:mm"));

Pattern Reference

Symbol Meaning Example

yyyy 4-digit year 2024

yy 2-digit year 24

MM 2-digit month 01

MMM Short month name Jan

MMMM Full month name January

dd 2-digit day 15

Page 11
d Day (no padding) 5

HH Hour (24h, 00–23) 10

hh Hour (12h, 01–12) 10

mm Minutes (00–59) 30

ss Seconds (00–59) 45

SSS Milliseconds 123

a AM / PM AM

EEE Short day name Mon

EEEE Full day name Monday

z Timezone name IST

Z Timezone offset +0530

VV Zone ID Asia/Kolkata

Page 12
11. Practical Examples

Age Calculator
public static String calculateAge(LocalDate dob) {
Period age = [Link](dob, [Link]());
return [Link]() + " years, "
+ [Link]() + " months, "
+ [Link]() + " days";
}

calculateAge([Link](2000, 5, 15));
// e.g. "24 years, 1 months, 10 days"

Next Business Day


public static LocalDate nextBusinessDay(LocalDate date) {
LocalDate next = [Link](1);
while ([Link]() == [Link] ||
[Link]() == [Link]) {
next = [Link](1);
}
return next;
}

Meeting Scheduler — Multi Timezone


LocalDateTime meetingIST = [Link](2024, 6, 15, 14, 30);
ZonedDateTime kolkata = [Link]([Link]("Asia/Kolkata"));

ZonedDateTime london = [Link]([Link]("Europe/London"));


ZonedDateTime newYork = [Link]([Link]("America/New_York"));
ZonedDateTime tokyo = [Link]([Link]("Asia/Tokyo"));

[Link]("Kolkata : " + [Link]([Link]("hh:mm a z"


)));
[Link]("London : " + [Link]([Link]("hh:mm a z")
));
[Link]("New York: " + [Link]([Link]("hh:mm a z"
)));
[Link]("Tokyo : " + [Link]([Link]("hh:mm a z"))
);

Stopwatch — Measure Execution Time


Instant start = [Link]();

// ... code to measure ...


[Link](1500);

Instant end = [Link]();


Duration elapsed = [Link](start, end);

[Link]("Elapsed: " + [Link]() + " ms");


// Elapsed: 1502 ms

Page 13
Days Until Deadline
LocalDate deadline = [Link](2024, 12, 31);
LocalDate today = [Link]();

long daysLeft = [Link](today, deadline);


[Link]("Days until deadline: " + daysLeft);

Page 14
12. ChronoUnit — Measuring Differences
ChronoUnit provides a clean way to calculate the difference between two dates/times in a specific unit.
LocalDate d1 = [Link](2024, 1, 1);
LocalDate d2 = [Link](2024, 12, 31);

[Link](d1, d2) // 365


[Link](d1, d2) // 52
[Link](d1, d2) // 11
[Link](d1, d2) // 0

LocalTime t1 = [Link](9, 0);


LocalTime t2 = [Link](17, 30);
[Link](t1, t2) // 8
[Link](t1, t2) // 510

ChronoUnit Used With

NANOS, MICROS, MILLIS Instant, LocalTime, LocalDateTime

SECONDS, MINUTES, HOURS Instant, LocalTime, LocalDateTime

HALF_DAYS, DAYS LocalDate, LocalDateTime

WEEKS, MONTHS, YEARS LocalDate, LocalDateTime

DECADES, CENTURIES, MILLENNIA LocalDate

Page 15
13. Quick Reference Cheat Sheet

When to Use Which Class

Scenario Use

Store a birthday / anniversary LocalDate

Store business opening hours LocalTime

Log file timestamp (no TZ) LocalDateTime

Global meeting scheduler ZonedDateTime

Database / API timestamp Instant

Calculate age [Link](dob, today)

Measure execution time [Link](start, end)

Format for display [Link](...)

Days between two dates [Link](d1, d2)

Common Gotchas
• Immutability — always assign the result: date = [Link](1), not just
[Link](1).
• ZonedDateTime vs LocalDateTime — never convert between timezones using LocalDateTime; use
ZonedDateTime.
• Instant is always UTC — convert to ZonedDateTime before displaying to users.
• Period vs Duration — Period for calendar differences (days/months/years), Duration for time
differences.
• Parse format must match exactly — parse("15-01-2024", ofPattern("dd/MM/yyyy"))
will throw DateTimeParseException.
• Thread safety — all [Link] classes are immutable and thread-safe; safe to share as constants.

Key Method Prefixes

Prefix Meaning Example

of() Static factory — create from values [Link](2024,1,15)

now() Static factory — current date/time [Link]()

parse() Static factory — from string [Link]("2024-01-15")

get() Access a field [Link]()

with() Return copy with one field changed [Link](2025)

plus() Return copy with amount added [Link](10)

minus() Return copy with amount subtracted [Link](1)

Page 16
to() Convert to another type [Link]()

at() Combine with another object [Link](10,30)

format() Format to string [Link](formatter)

Page 17
[Link] — Key Takeaways
✔ All classes in [Link] are immutable — every operation returns a new object.
✔ Use LocalDate/Time for most cases where timezone is not needed.
✔ Use ZonedDateTime whenever timezone matters.
✔ Period for date differences · Duration for time differences.
✔ Always use DateTimeFormatter for formatting — never concatenate manually.
✔ Instant is for machine timestamps, not human-readable output.
✔ Use ChronoUnit for clean single-unit differences (days, months, hours).

Java 8+ · [Link] package · ISO-8601 compliant

Page 18

You might also like