You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将java.util.Date按dd/MM/yyyy格式返回?TimeAgo类时间格式修改

问题原因

你当前代码中超过三周的逻辑分支直接调用了Date.toString()方法,该方法会输出JDK默认的日期格式,不符合你需要的dd/MM/yyyy格式,只需修改该分支的日期格式化逻辑即可。

修正后代码

static class TimeAgo {
    private static final int SECOND_MILLIS = 1000;
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
    private static final int WEEK_MILLIS = 7 * DAY_MILLIS ;
    // 定义目标日期格式,需要带时间可以改成 dd/MM/yyyy HH:mm
    private static final String DATE_PATTERN = "dd/MM/yyyy";

    public static String getTimeAgo(long time) {
        if (time < 1000000000000L) {
            time *= 1000;
        }

        long now = System.currentTimeMillis();
        if (time > now || time <= 0) {
            return null;
        }

        final long diff = now - time;
        if (diff < MINUTE_MILLIS) {
            return "刚刚";
        } else if (diff < 2 * MINUTE_MILLIS) {
            return "1分钟前";
        } else if (diff < 50 * MINUTE_MILLIS) {
            return diff / MINUTE_MILLIS + "分钟前";
        } else if (diff < 90 * MINUTE_MILLIS) {
            return "1小时前";
        } else if (diff < 24 * HOUR_MILLIS) {
            return diff / HOUR_MILLIS + "小时前";
        } else if (diff < 48 * HOUR_MILLIS) {
            return "昨天";
        } else if (diff < 72 * HOUR_MILLIS) {
            return "1天前";
        } else if (diff < 7 * DAY_MILLIS) {
            return diff / DAY_MILLIS + "天前";
        } else if (diff < 2 * WEEK_MILLIS) {
            return "1周前";
        } else if (diff < WEEK_MILLIS * 3) {
            return diff / WEEK_MILLIS + "周前";
        } else {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_PATTERN);
            return sdf.format(new java.util.Date(time));
        }
    }
}

注意事项

如果你的项目使用Java 8及以上版本,更推荐用线程安全的DateTimeFormatter替换非线程安全的SimpleDateFormat,避免多线程调用出现格式错乱问题,修改方式如下:

  1. 在类中全局定义格式化器(可复用):
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_PATTERN);
  1. 把else分支的代码替换为:
return Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault()).format(DATE_FORMATTER);

内容的提问来源于stack exchange,提问作者Don Benito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:54:05