Back to Stream Practice: Employee Analysis
Q19Question 19 of 43

Calculate the difference in days between two employees' joining dates using ChronoUnit.DAYS.between

Key Concepts
  • ChronoUnit.DAYS.between(startDate, endDate) returns the number of days between two LocalDate values
  • The result is signed: negative if endDate is before startDate
  • Period.between gives years/months/days breakdown; ChronoUnit gives a single total in one unit
  • Use Math.abs() if you want the absolute difference regardless of order
  • ChronoUnit.MONTHS.between and YEARS.between work similarly for other units
  • Combine with streams to compute pairwise differences or tenure calculations

Definition

ChronoUnit.DAYS.between(dateA, dateB) returns the total number of days between two LocalDate values as a long, with correct leap-year handling.
  • ChronoUnit.DAYS.between(start, end) returns long representing the total days from start to end.
  • Signed result: positive if end is after start, negative if before.
  • Period.between gives a breakdown in years, months, and days; ChronoUnit gives a flat total.
  • Other units: MONTHS.between, YEARS.between, WEEKS.between work the same way.
  • Leap years: handled automatically by the LocalDate calendar model.

Rajesh and Priya at the National Bank of India want to know how many days apart their joining dates are. ChronoUnit.DAYS.between counts every calendar day from Rajesh's start to Priya's start, including leap days.

Understanding the Concepts

What does this question ask?

The interviewer wants you to compute the difference between two dates using the java.time API. This tests ChronoUnit usage, signed vs absolute differences, and the distinction between ChronoUnit and Period.

How do you calculate the difference in days?

JAVA
package com.bank.hr;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

public class DateDifference {
    public static void main(String[] args) {
        LocalDate rajeshJoined = LocalDate.of(2015, 3, 1);
        LocalDate priyaJoined = LocalDate.of(2021, 6, 15);

        long daysBetween = ChronoUnit.DAYS.between(
            rajeshJoined, priyaJoined);

        System.out.println("Days between: " + daysBetween);
        System.out.println("Rajesh joined " + daysBetween
            + " days before Priya");
    }
}
TEXT
Days between: 2298
Rajesh joined 2298 days before Priya

How is ChronoUnit different from Period?

| Feature | ChronoUnit.DAYS.between | Period.between |
|---|---|---|
| Returns | long (flat total days) | Period (years + months + days) |
| Example | 2298 | 6 years, 3 months, 14 days |
| Use case | Total days for calculations | Human-readable breakdown |
| Other units | MONTHS, YEARS, WEEKS, HOURS | Only years/months/days |

JAVA
import java.time.Period;
import java.time.temporal.ChronoUnit;

LocalDate start = LocalDate.of(2015, 3, 1);
LocalDate end = LocalDate.of(2021, 6, 15);

// ChronoUnit: flat total
long totalDays = ChronoUnit.DAYS.between(start, end);    // 2298
long totalMonths = ChronoUnit.MONTHS.between(start, end); // 75
long totalYears = ChronoUnit.YEARS.between(start, end);   // 6

// Period: breakdown
Period period = Period.between(start, end);
System.out.println(period.getYears() + "y "
    + period.getMonths() + "m "
    + period.getDays() + "d");
// 6y 3m 14d

How do you use this with streams for pairwise comparison?

JAVA
package com.bank.hr;

import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

public class TenureComparison {
    public static void main(String[] args) {
        List<Employee> employees = Employee.getSampleEmployees();

        // Compute tenure in days for each employee
        employees.stream()
            .sorted(Comparator.comparing(Employee::getJoinDate))
            .forEach(e -> {
                long tenure = ChronoUnit.DAYS.between(
                    e.getJoinDate(), java.time.LocalDate.now());
                System.out.printf("%s: %d days (%.1f years)%n",
                    e.getName(), tenure, tenure / 365.25);
            });
    }
}

What are common mistakes?

Mistake 1: reversing the argument order and getting a negative result.

JAVA
// Returns negative when start is after end
long negative = ChronoUnit.DAYS.between(
    LocalDate.of(2021, 6, 15),
    LocalDate.of(2015, 3, 1));  // -2298

// Use Math.abs for absolute difference
long absolute = Math.abs(ChronoUnit.DAYS.between(
    LocalDate.of(2021, 6, 15),
    LocalDate.of(2015, 3, 1)));  // 2298

Mistake 2: using Period.getDays() expecting total days.

JAVA
// WRONG: Period.getDays() returns only the days component, not total
Period p = Period.between(
    LocalDate.of(2015, 3, 1),
    LocalDate.of(2021, 6, 15));
int wrong = p.getDays();  // 14 (just the days part, not 2298!)

// CORRECT: use ChronoUnit for total
long correct = ChronoUnit.DAYS.between(
    LocalDate.of(2015, 3, 1),
    LocalDate.of(2021, 6, 15));  // 2298

What are common interview follow-up questions?

  • "How do you find the pair of employees with the largest joining date gap?" Compare all pairs using nested streams or a sorted list.
  • "How do you compute average tenure?" Map each employee to tenure days, then use averagingLong.
  • "How do you handle time zones?" Use ZonedDateTime and ChronoUnit.DAYS.between still works.

Visual Overview

DIAGRAM
  ChronoUnit.DAYS.between(start, end):

  start: 2015-03-01    end: 2021-06-15
  │                     │
  ├─ 2015: 306 days ───→│
  ├─ 2016: 366 days ───→│  (leap year)
  ├─ 2017: 365 days ───→│
  ├─ 2018: 365 days ───→│
  ├─ 2019: 365 days ───→│
  ├─ 2020: 366 days ───→│  (leap year)
  ├─ 2021: 165 days ───→│  (Jan-Jun 15)
  └─ Total: 2298 days

  Period.between: 6 years, 3 months, 14 days
  ChronoUnit: 2298 (flat total)

Key Takeaway

ChronoUnit.DAYS.between computes the total number of days between two LocalDate values as a flat long. The result is signed: positive when the end date is after the start, negative when before. Use Math.abs() if you need the absolute difference regardless of argument order.

Period.between gives a human-readable breakdown in years, months, and days. The critical mistake is calling Period.getDays() expecting the total: it returns only the days component (14), not the total (2298). Use ChronoUnit for flat totals.

In banking tenure calculations, map each employee to their tenure using ChronoUnit.DAYS.between(joinDate, LocalDate.now()) and then aggregate with averagingLong or summarizingLong for dashboard statistics.

Remember one sentence: ChronoUnit.DAYS.between gives a flat total of days between two dates, while Period.between gives a years-months-days breakdown.

---

Share
Use ← → arrow keys to navigate