← 中文资源

简体中文版本

由 Duration 生成 time ago 标签

把过去的 Instant 转成 time ago 标签:一分钟内 just now,一天内用 Duration,跨天后改用日期差避开夏令时偏差,并处理单复数。

阅读英文原文

实现说明

真正干活的是类 TimeAgoLabels和函数 plural、timeAgo、main,其余都是接线。 for (String past : pasts) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • main 的演示流程是 timeAgo——跑一遍文件,这条流程从头到尾可见。

常见问题

「由 Duration 生成 time ago 标签」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

主要签名是 static String plural(long amount, String unit)

核心语句

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

代码示例

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));
        }
    }
}