1. List out Java 8 Date/Time API - Practical Formulas & Methods (Included this question to make the preparation easy)
  2. What is Java 8 Date/Time API? Why better than old Date/Calendar?
  3. Key classes: LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant.
  4. Common operations: plus/minus, Period, Duration, formatting/parsing.
  5. Time zones and ZoneId — examples.
  6. Difference between Period and Duration.
  7. How to handle legacy Date with new API (toInstant, from).
  8. Best practices for Date/Time in production (immutability, thread-safety).

List out Java 8 Date/Time API - Practical Formulas & Methods

Organized the Java 8 Date/Time APIs into the following key categories for easy memorization 

  1. Date, Time, DateTime – Classes/Methods (No Zone)
  2. DateTime with Zone – Classes/Methods
  3. Formatting/Parsing
  4. Common Operations – plus/minus
  5. Periods (Date-based differences)
  6. Duration (Time-based differences)
  7. Convert Legacy Date to New API
  8. Convert New API to Legacy Date

1. Date, Time, DateTime – Classes/Methods (No Zone)

ClassMethod/ExampleOutput (DD-MM-YYYY)Use Case
LocalDateLocalDate.now()31-01-2026Current date only (birthday, holiday)

LocalDate.of(2026, 1, 31)31-01-2026Specific date
LocalTimeLocalTime.now()14:30:25Current time only (meeting time)

LocalTime.of(14, 30)14:30Specific time
LocalDateTimeLocalDateTime.now()31-01-2026T14:30:25Current date + time (no zone)

LocalDateTime.of(2026, 1, 31, 14, 30)31-01-2026T14:30Specific date-time

2. Date/Time with Zone – Classes/Methods

ClassMethod/ExampleOutput (DD-MM-YYYY)Use Case
ZoneIdZoneId.of("Asia/Kolkata")Asia/KolkataDefine timezone
ZonedDateTimeZonedDateTime.now()31-01-2026T14:30:25+05:30[Asia/Kolkata]Current date-time with zone

ZonedDateTime.now(ZoneId.of("America/New_York"))31-01-2026T04:00:25-05:00[America/New_York]Specific zone time

ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Kolkata"))31-01-2026T14:30+05:30[Asia/Kolkata]Attach zone to LocalDateTime
InstantInstant.now()2026-01-31T09:00:25ZUTC machine timestamp

3. Formatting/Parsing

Class/MethodExample CodeOutput / ResultUse Case
DateTimeFormatterDateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm")(formatter object)Custom pattern
formatlocalDateTime.format(formatter)31-01-2026 14:30Date → String
parseLocalDateTime.parse("31-01-2026 14:30", formatter)LocalDateTime objectString → DateTime
Pre-definedDateTimeFormatter.ISO_LOCAL_DATE.format(localDate)2026-01-31Standard ISO format

4. Common Operations – plus/minus

OperationExample CodeOutput (DD-MM-YYYY)Use Case
plusdate.plusDays(10)10-02-2026Add days

dateTime.plusMonths(2)31-03-2026T14:30Add months
minusdate.minusYears(1)31-01-2025Subtract years
with (replace)date.withDayOfMonth(15)15-01-2026Change day

5. Periods (Date-based)

Class/MethodExample CodeOutputUse Case
PeriodPeriod.between(LocalDate.of(1990, 5, 15), LocalDate.of(2026, 1, 31))P35Y8M16DCalculate age

Period.ofMonths(3)P3MFixed period

date.plus(period)30-04-2026Add period

6. Duration (Time-based)

Class/MethodExample CodeOutputUse Case
DurationDuration.between(LocalTime.of(10, 0), LocalTime.of(15, 30))PT5H30MTime difference

Duration.ofHours(8)PT8HFixed duration

time.plus(duration)22:30Add duration

7. Convert Legacy Date to New API

MethodExample CodeResultUse Case
Date → NewDate legacy = new Date(); Instant instant = legacy.toInstant(); LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());LocalDateTime (e.g., 31-01-2026T14:30)Migrate old code to new API

8. Convert New API to Legacy Date

MethodExample CodeResultUse Case
New → DateLocalDateTime ldt = LocalDateTime.of(2026, 1, 31, 14, 30); Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant(); Date legacy = Date.from(instant);java.util.Date objectUse with legacy libraries

Memory Tip
=> Local = no zone
=> Zoned = with zone
=> Instant = UTC machine time
=> Period = date diff (years/months/days)
=> Duration = time diff (hours/minutes/seconds)

What is Java 8 Date/Time API? Why better than old Date/Calendar?

=> Java 8 Date/Time API a immutable and thread safe API for handling dates, time, duration and periods to address the long standing flaws in the legacy classes java.util.date, java.util.calendar. 

=> java.time is designed for production — immutable and thread-safe by default. 

Java 8 Date/Time API

Old Date, Calander classes

Package : java.time

Package : java.util.Date, Java.util.Calander

All classes are immutable. ie. Operations return new instances

Date and Calnder are mutable. ie. modifying one instance can affect others unexpectedly

Thread safe and so ideal for concurrent applications

Concurrent modifications lead to bugs

=> Separate classes for date, time, date-time, with consistent methods

=> Better time zone support. Ie ZoneId and ZonedDateTime handle DST and offsets correctly

(DST – Daylight Saving Time)

=> Built-in support for periods, durations, formatting/parsing

=> No separate methods for date, time, timezone concepts.

=> Date represents both date and time but confusing methods (eg. months 0-based)

=> Timezone handling is poor, confusing and buggy

=> Calander has many deprecated methods, poor internationalization 

Use case : Always prefer java.time over legacy classes

Cannot prefer over Java 8 Date/Time API

Example :

// New way (immutable, fluent) LocalDate date = LocalDate.now(); LocalDate newDate = date.plusDays(10); // Original date unchanged



Example :

// Old way (mutable, error-prone) Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, 10); // Modifies cal

Key classes: LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Instant.

=> The java.time package has specialized classes for different needs

=> LocalDate: Date without time or timezone (year-month-day).
Example: Birthday, holiday.

LocalDate date = LocalDate.of(2025, 12, 26);

=> LocalTime: Time without date or timezone (hour-minute-second-nano).
Example: Meeting time in local context.

LocalTime time = LocalTime.of(14, 30);

=> LocalDateTime: Combination of LocalDate + LocalTime (no timezone).
Example: Event timestamp without zone.

LocalDateTime dt = LocalDateTime.now();

=> ZonedDateTime: LocalDateTime + timezone (handles DST, offsets).
Example: Global meeting time.

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

=> Instant: Machine timestamp (UTC, seconds + nanos since epoch).
Example: Logging, timestamps in databases.

Instant instant = Instant.now();

=> Best Practice: Use the most specific class needed — LocalDateTime for most cases, ZonedDateTime for zone-aware, Instant for storage.

Common operations: plus/minus, Period, Duration, formatting/parsing.

=> plus/minus: Chainable methods to add/subtract units.

LocalDate date = LocalDate.now();
LocalDate future = date.plusDays(10).plusMonths(2).minusYears(1);

 => Period: Date-based amount (years, months, days).

Period period = Period.between(LocalDate.of(2025, 1, 1), LocalDate.of(2026, 1, 1)); // P1Y
LocalDate newDate = date.plus(period);

=> Duration: Time-based amount (hours, minutes, seconds, nanos).

Duration duration = Duration.ofHours(5);
LocalTime newTime = time.plus(duration);

=> Formatting/Parsing:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
String text = zdt.format(formatter);
ZonedDateTime parsed = ZonedDateTime.parse(text, formatter);

=> Best Practice: Use DateTimeFormatter for custom formats; pre-defined ISO_LOCAL_DATE for standard.

Time zones and ZoneId — examples.

=> ZoneId: Represents timezone (e.g., "Asia/Kolkata", "America/New_York").

ZoneId kolkata = ZoneId.of("Asia/Kolkata");
ZoneId ny = ZoneId.of("America/New_York");

=> With ZonedDateTime:

ZonedDateTime kolkataTime = ZonedDateTime.now(kolkata);
ZonedDateTime nyTime = kolkataTime.withZoneSameInstant(ny);  // Convert to NY time

=> ZoneOffset: Fixed offset (e.g., +05:30 for IST)

ZoneOffset ist = ZoneOffset.of("+05:30");

=> Best Practice: Store in UTC (Instant), display in user's ZoneId.

Difference between Period and Duration.

Aspect

Period

Duration

Unit

Date-based 
(years, months, days)

Time-based 
(hours, minutes, seconds, nanos)

Use Case

Human dates (birthdays, anniversaries)

Machine time (timers, intervals)

Example

Period.ofYears(1) = P1Y

Duration.ofHours(24) = PT24H

Add to

LocalDate, LocalDateTime

LocalTime, LocalDateTime, Instant

Precision

Calendar differences (handles months/years)

Exact nanos

Code Example : 

Period p = Period.ofDays(30);  // 30 days
Duration d = Duration.ofDays(30);  // Exactly 30*24 hours 

=> Best Practice: Use Period for date differences, Duration for time.

How to handle legacy Date with new API (toInstant, from).

Convert between legacy and new API

=> Legacy Date/Calendar to new:

Date oldDate = new Date();
Instant instant = oldDate.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());

=> New to legacy:

LocalDateTime ldt = LocalDateTime.now();
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();
Date legacyDate = Date.from(instant);

=> Best Practice: Convert at boundaries (e.g., DB/API) — use new API internally.

Best practices for Date/Time in production (immutability, thread-safety).

=> Immutability: All java.time classes are immutable — never modify, always create new instances.
=> Thread-Safety: Safe for concurrent use (no synchronization needed).
=> Store in UTC: Use Instant or OFFSET for storage.
=> Display in User Zone: Convert with ZoneId for UI.
=> Avoid Legacy: Don't mix Date/Calendar unless forced.
=> Use DateTimeFormatter Carefully: Pre-defined ISO formats or thread-safe custom (not shared mutable formatter).
=> Handle Nulls: Use Optional or default values.
=> Code Example (Thread-Safe):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String text = localDate.format(formatter);  // Safe in multi-thread

_______________________________________________________________

Practice the following coding exercises

  1. Reduce to sum of integers in list.
  2. Reduce to product of integers.
  3. Reduce to concatenate strings with delimiter.
  4. FlatMap: Flatten List<List<String>> to List<String>.
  5. FlatMap: Flatten List<Optional<String>> to List<String>.
  6. Generate 10 random numbers using Stream.generate + limit.
  7. Generate even numbers sequence using Stream.iterate + limit.
  8. Create LocalDate for today and print.
  9. Add 10 days to today's date using plusDays.
  10. Calculate age from birth date using Period.between.
  11. Parse string to LocalDateTime using DateTimeFormatter.
  12. Format LocalDateTime to custom pattern (e.g., "dd-MM-yyyy HH:mm").
  13. Get current time in different time zones (ZoneId.of("Asia/Kolkata"), "America/New_York").
  14. Convert old Date to LocalDateTime.
  15. Duration between two LocalDateTime.
  16. Find max/min date in list of LocalDate.
  17. Group dates by month using groupingBy.
  18. Infinite stream of Fibonacci numbers (limit 10).
  19. Stream of primes (generate + filter + limit).
  20. Debug Stream with peek (print intermediate values).