72

我需要计算从一个特定日期到现在所经过的时间,并以与 StackOverflow 问题相同的格式显示,即:

15s ago
2min ago
2hours ago
2days ago
25th Dec 08

你知道如何使用 Java Joda-Time来实现它吗?是否有已经实现它的辅助方法,或者我应该自己编写算法?

4

6 回答 6

116

要使用 JodaTime 计算经过的时间,请使用Period. 要将经过时间格式化为所需的人工表示,请使用PeriodFormatter您可以构建的PeriodFormatterBuilder.

这是一个启动示例:

DateTime myBirthDate = new DateTime(1978, 3, 26, 12, 35, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendSeconds().appendSuffix(" seconds ago\n")
    .appendMinutes().appendSuffix(" minutes ago\n")
    .appendHours().appendSuffix(" hours ago\n")
    .appendDays().appendSuffix(" days ago\n")
    .appendWeeks().appendSuffix(" weeks ago\n")
    .appendMonths().appendSuffix(" months ago\n")
    .appendYears().appendSuffix(" years ago\n")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed);

这现在打印

3 秒前
51 分钟前
7 小时前
6 天前
10 个月前
31年前

(咳,老,咳)你看我也考虑了几个月和几年,并将它配置为在那些为零时忽略这些值。

于 2010-02-01T20:29:15.763 回答
20

使用PrettyTime表示简单的经过时间。

我尝试了 HumanTime,@sfussenegger 回答并使用了 JodaTime,Period但我发现的人类可读的经过时间最简单和最干净的方法是PrettyTime库。

下面是几个简单的输入和输出示例:

五分钟前

DateTime fiveMinutesAgo = DateTime.now().minusMinutes( 5 );

new PrettyTime().format( fiveMinutesAgo.toDate() );

// Outputs: "5 minutes ago"

不久以前

DateTime birthday = new DateTime(1978, 3, 26, 12, 35, 0, 0);

new PrettyTime().format( birthday.toDate() );

// Outputs: "4 decades ago"

注意:我尝试过使用该库更精确的功能,但它会产生一些奇怪的结果,因此请小心使用它,并且不要危及生命的项目。

J.P

于 2014-08-16T20:38:55.327 回答
11

您可以使用 PeriodFormatter 做到这一点,但您不必像其他答案那样努力制作自己的 PeriodFormatBuilder 。如果适合您的情况,您可以使用默认格式化程序:

Period period = new Period(startDate, endDate);
System.out.println(PeriodFormat.getDefault().print(period))

(关于类似问题的这个答案的提示,我正在交叉发布以方便发现)

于 2014-02-07T11:53:10.290 回答
8

有一个名为HumanTime的小助手类,我很满意。

于 2010-02-01T20:13:09.107 回答
0

这是使用 mysql 时间戳来获取到现在的经过时间。单数和复数被管理。只显示最大时间。

注意:设置您自己的时区。

String getElapsedTime(String strMysqlTimestamp) {
    
    DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.S");
    DateTime mysqlDate = formatter.parseDateTime(strMysqlTimestamp).
                         withZone(DateTimeZone.forID("Asia/Kuala_Lumpur"));
    
    DateTime now = new DateTime();
    Period period = new Period(mysqlDate, now);
    
    int seconds = period.getSeconds();
    int minutes = period.getMinutes();
    int hours = period.getHours();
    int days = period.getDays();
    int weeks = period.getWeeks();
    int months = period.getMonths();
    int years = period.getYears();
    
    String elapsedTime = "";
    if (years != 0)
        if (years == 1)
            elapsedTime = years + " year ago";
        else
            elapsedTime = years + " years ago";
    else if (months != 0)
        if (months == 1)
            elapsedTime = months + " month ago";
        else
            elapsedTime = months + " months ago";
    else if (weeks != 0)
        if (weeks == 1)
            elapsedTime = weeks + " week ago";
        else
            elapsedTime = weeks + " weeks ago";
    else if (days != 0)
        if (days == 1)
            elapsedTime = days + " day ago";
        else
            elapsedTime = days + " days ago";
    else if (hours != 0)
        if (hours == 1)
            elapsedTime = hours + " hour ago";
        else
            elapsedTime = hours + " hours ago";
    else if (minutes != 0)
        if (minutes == 1)
            elapsedTime = minutes + " minute ago";
        else
            elapsedTime = minutes + " minutes ago";
    else if (seconds != 0)
        if (seconds == 1)
            elapsedTime = seconds + " second ago";
        else
            elapsedTime = seconds + " seconds ago";   
    
    return elapsedTime;
} 
于 2021-01-04T17:25:07.157 回答
0

这是我的解决方案,使用joda time.

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;

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 "just now";
    }
    else if(diff < 2 * MINUTE_MILLIS)
    {
        return "a minute ago";
    }
    else if(diff < 50 * MINUTE_MILLIS)
    {
        return diff / MINUTE_MILLIS + " minutes ago";
    }
    else if(diff < 90 * MINUTE_MILLIS)
    {
        return "an hour ago";
    }
    else if(diff < 24 * HOUR_MILLIS)
    {
        return diff / HOUR_MILLIS + " hours ago";
    }
    else if(diff < 48 * HOUR_MILLIS)
    {
        return "yesterday";
    }
    else
    {
        return diff / DAY_MILLIS + " days ago";
    }
}

使用方法:

只需调用方法并传入时间即可milliseconds

例如

long now = System.currentTimeMillis();
getTimeAgo(now);
于 2021-06-03T12:24:27.533 回答