首页 > 解决方案 > How to calculate relative time spans using Java (code converting problem)?

问题描述

I decided to give myself a challenge on Java that implements this question's achievement.

The things I have to do is get LocalDateTime, convert the same code from the linked question's answers, then receiving a string from the function.

Here's what I've done so far:

public static String relTime(LocalDateTime now)
{
    // accepted answer converted to Java
    const int min = 60 * SECOND;
    const int hour = 60 * MINUTE;
    const int day = 24 * HOUR;
    const int mon = 30 * DAY;
    
    // still don't know how to convert this method
    var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
    double delta = Math.Abs(ts.TotalSeconds);
    
    if (delta < 1 * MINUTE)
        return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";

    if (delta < 2 * MINUTE)
        return "a minute ago";
    
    if (delta < 45 * MINUTE)
        return ts.Minutes + " minutes ago";
    
    if (delta < 90 * MINUTE)
        return "an hour ago";
    
    if (delta < 24 * HOUR)
        return ts.Hours + " hours ago";

    if (delta < 48 * HOUR)
        return "yesterday";
    
    if (delta < 30 * DAY)
        return ts.Days + " days ago";
    
    if (delta < 12 * MONTH)
    {
        int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
        return months <= 1 ? "one month ago" : months + " months ago";
    }
    else
    {
        int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
        return years <= 1 ? "one year ago" : years + " years ago";
    }
}

The only problem that I should encounter is from var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);.

Although I read 2 questions from Stack Overflow finding equivalents of TimeSpan and Ticks, I baely have any ideas how to properly convert the line of code. Also, I have to get a double which will need math.abs() to get TotalSeconds which I can't really find a proper way to deal with either, but I did find ZoneOffset.ofTotalSeconds and still don't know how to deal with it.

So how can I convert this properly?

var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

标签: javadatetimerelative-time-span

解决方案


You could use SimpleDateFormat to create a nice display format (use something like "HH hours, mm minutes and ss seconds ago" for the format (not sure if this exact example works)). You could also use Instant to get the current time, and you can use Instant.now().minusSeconds(Instant.now().minusSeconds(seconds).getEpochSeconds()) for the time difference (or just use System.currentTimeMillis() and multiply by 1000).

Alternatively, you could use Duration and write a custom display format using getSeconds() and getHours() etc.


推荐阅读