简体   繁体   English

如何使用 Joda-Time 计算从现在起经过的时间?

[英]How to calculate elapsed time from now with Joda-Time?

I need to calculate the time elapsed from one specific date till now and display it with the same format as StackOverflow questions, ie:我需要计算从一个特定日期到现在所经过时间,并以与 StackOverflow 问题相同的格式显示它,即:

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

Do you know how to achieve it with the Java Joda-Time library ?您知道如何使用 Java Joda-Time实现它吗? Is there a helper method out there that already implements it, or should I write the algorithm myself?是否有已经实现它的辅助方法,还是我应该自己编写算法?

To calculate the elapsed time with JodaTime, use Period .要使用 JodaTime 计算经过时间,请使用Period To format the elapsed time in the desired human representation, use PeriodFormatter which you can build by PeriodFormatterBuilder .要在所需的人类表示中格式化经过的时间,请使用PeriodFormatter ,您可以通过PeriodFormatterBuilder构建PeriodFormatterBuilder

Here's a kickoff example:这是一个启动示例:

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

This prints by now这现在打印

3 seconds ago
51 minutes ago
7 hours ago
6 days ago
10 months ago
31 years ago

(Cough, old, cough) You see that I've taken months and years into account as well and configured it to omit the values when those are zero. (咳,老,咳)你看,我也考虑了几个月和几年,并将其配置为在这些值为零时省略这些值。

Use PrettyTime for Simple Elapsed Time.使用PrettyTime表示简单的经过时间。

I tried HumanTime as @sfussenegger answered and using JodaTime's Period but the easiest and cleanest method for human readable elapsed time that I found was the PrettyTime library.我尝试了HumanTime,因为@sfussenegger 回答并使用了 JodaTime 的Period但我发现的人类可读经过时间的最简单和最干净的方法是PrettyTime库。

Here's a couple of simple examples with input and output:下面是几个带有输入和输出的简单示例:

Five Minutes Ago五分钟前

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

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

// Outputs: "5 minutes ago"

Awhile Ago不久以前

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

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

// Outputs: "4 decades ago"

CAUTION: I've tried playing around with the library's more precise functionality, but it produces some odd results so use it with care and in non-life threatening projects.注意:我曾尝试使用库的更精确的功能,但它会产生一些奇怪的结果,因此请谨慎使用它并在非危及生命的项目中使用它。

JP J.P

You can do this with a PeriodFormatter but you don't have to go to the effort of making your own PeriodFormatBuilder as in other answers .您可以使用 PeriodFormatter 来做到这一点,但您不必像其他答案一样努力制作自己的 PeriodFormatBuilder 。 If it suits your case, you can just use the default formatter:如果它适合你的情况,你可以使用默认的格式化程序:

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

(hat tip to this answer on a similar question, I'm cross-posting for discoverability) (对类似问题的这个答案的提示,我交叉发布以提高可发现性)

有一个叫做HumanTime的小助手类,我很满意。

This is using mysql timestamp to get elapsed time to now.这是使用 mysql 时间戳来获取到现在的经过时间。 Singular and plular is managed.单数和复数被管理。 Only display the max time.只显示最大时间。

NOTE: set your own timezone.注意:设置您自己的时区。

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

Here is my solution , using joda time .这是我的解决方案,使用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";
    }
}

How to use the method:使用方法:

Just call the method and pass in time in milliseconds .只需调用该方法并以milliseconds传递时间。

For example :例如

long now = System.currentTimeMillis();
getTimeAgo(now);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM