Time Ago Labels From Duration

Turn a past Instant into human time ago labels, using Duration for minutes and hours and date arithmetic once a day has elapsed.

JavaData Fetching

Code

snippet
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;

public class TimeAgoLabels {

    // human "time ago" labels: minutes and hours from Duration, days and beyond from dates
    static String plural(long amount, String unit) {
        return amount + " " + unit + (amount == 1 ? "" : "s") + " ago";
    }

    static String timeAgo(Instant then, Instant now) {
        Duration elapsed = Duration.between(then, now);
        if (elapsed.isNegative() || elapsed.toMinutes() < 1) {
            return "just now";
        }
        if (elapsed.toMinutes() < 60) {
            return plural(elapsed.toMinutes(), "minute");
        }
        if (elapsed.toHours() < 24) {
            return plural(elapsed.toHours(), "hour");
        }
        // use the date difference across day boundaries so DST shifts never skew a whole day away from 86400 seconds
        ZonedDateTime from = then.atZone(ZoneId.of("America/New_York"));
        ZonedDateTime to = now.atZone(ZoneId.of("America/New_York"));
        long days = ChronoUnit.DAYS.between(from, to);
        if (days < 7) {
            return plural(days, "day");
        }
        if (days < 30) {
            return plural(days / 7, "week");
        }
        long months = ChronoUnit.MONTHS.between(from, to);
        if (months < 12) {
            return plural(months, "month");
        }
        return plural(days / 365, "year");
    }

    public static void main(String[] args) {
        Instant now = Instant.parse("2026-11-21T12:00:00Z");
        String[] pasts = {
                "2026-11-21T11:59:30Z", "2026-11-21T11:35:00Z",
                "2026-11-21T06:00:00Z", "2026-11-20T12:00:00Z",
                "2026-11-10T12:00:00Z", "2026-10-01T12:00:00Z",
                "2025-01-01T12:00:00Z"};
        for (String past : pasts) {
            System.out.println(past + " -> " + timeAgo(Instant.parse(past), now));
        }
    }
}

Inside the snippet

Under the hood: the class TimeAgoLabels and the functions plural, timeAgo and main.

Repetition is confined to for (String past : pasts) — the rest of the file is straight-line.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Putting it to use

The primary signature is static String plural(long amount, String unit)

main sequences timeAgo; executing the file runs that flow once.

The core lines of the flow

return amount + " " + unit + (amount == 1 ? "" : "s") + " ago";
return plural(elapsed.toMinutes(), "minute");
return plural(elapsed.toHours(), "hour");

Interactive Tools for This Topic

FAQ

How do you run Time Ago Labels From Duration?
Direct execution is enough; the script has no external requirements.