几秒前,几分钟前,几小时前,几天前,几月前,几年前的java实现

在代码开发的时候,特别是那种论坛啊什么的要返回几秒前,几分钟前,几小时前,几天前,几月前,几年前这样的时间格式,服务端那边只肯返回yyyy-MM-dd HH:mm:ss的格式,没办法,只能客户端加个转换了。

代码如下:

public class RelativeDateFormat {
private static final long ONE_MINUTE = 60000L;
private static final long ONE_HOUR = 3600000L;
private static final long ONE_DAY = 86400000L;
private static final long ONE_WEEK = 604800000L;

private static final String ONE_SECOND_AGO = "秒前";
private static final String ONE_MINUTE_AGO = "分钟前";
private static final String ONE_HOUR_AGO = "小时前";
private static final String ONE_DAY_AGO = "天前";
private static final String ONE_MONTH_AGO = "月前";
private static final String ONE_YEAR_AGO = "年前";

public static String format(Date date) {
    long delta = new Date().getTime() - date.getTime();
    if (delta  1L * ONE_MINUTE) {
        long seconds = toSeconds(delta);
        return (seconds = 0 ? 1 : seconds) + ONE_SECOND_AGO;
    }
    if (delta  45L * ONE_MINUTE) {
        long minutes = toMinutes(delta);
        return (minutes = 0 ? 1 : minutes) + ONE_MINUTE_AGO;
    }
    if (delta  24L * ONE_HOUR) {
        long hours = toHours(delta);
        return (hours = 0 ? 1 : hours) + ONE_HOUR_AGO;
    }
    if (delta  48L * ONE_HOUR) {
        return "昨天";
    }
    if (delta  30L * ONE_DAY) {
        long days = toDays(delta);
        return (days = 0 ? 1 : days) + ONE_DAY_AGO;
    }
    if (delta  12L * 4L * ONE_WEEK) {
        long months = toMonths(delta);
        return (months = 0 ? 1 : months) + ONE_MONTH_AGO;
    } else {
        long years = toYears(delta);
        return (years = 0 ? 1 : years) + ONE_YEAR_AGO;
    }
}

private static long toSeconds(long date) {
    return date / 1000L;
}

private static long toMinutes(long date) {
    return toSeconds(date) / 60L;
}

private static long toHours(long date) {
    return toMinutes(date) / 60L;
}

private static long toDays(long date) {
    return toHours(date) / 24L;
}

private static long toMonths(long date) {
    return toDays(date) / 30L;
}

private static long toYears(long date) {
    return toMonths(date) / 365L;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
调用的时候传入时间,今天是2016年1月20号

   SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
        date = format.parse("2015-11-11 18:35:35");
        System.out.println(RelativeDateFormat.format(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }

1
2
3
4
5
6
7
8
看打印的log,算出来是没问题的。
这里写图片描述

最新回复(0)
/jishuzKUalU16jVV4hvxk_2F0KbLdg3ALEYv6R_2F4b4osQ_3D_3D4488516
8