1

预期结果是“Last game 2h 12m ago”。或“3m 前的最后一场比赛。”。

目前它是“Last game 0d 2h 12m ago.”,我在 SimpleDateFormat 中找不到任何可以做到这一点的方法,我看到的最简单的解决方案是使用 StringBuilder,每次测试值是否为零。

代码示例:

public String getLastgame()
{
    long time = ((System.currentTimeMillis() / 60000) - this.config.getLastgameTime());

    return ("Last game " + (time / 60) + "h " + (time % 60) + "m ago.");
}
4

2 回答 2

2

您的时间以分钟为单位,因此,首先提取所有时间组件:

long oneYear = 60 * 24 * 365;
long oneDay = 60 * 24;
long oneHour = 60;

// extract years
int years = time / oneYear;
// update your time
time = time % oneYear;

// extract days
long days = time / oneDay;
// update your time
time = time % oneDay;

// extract hours    
long hours = time / oneHour;

// extract minutes (the remaining)
minutes = time % oneHour;

然后,构建你的字符串:

StringBuilder sb = new StringBuilder( "Last time " );
if ( years != 0 ) {
    sb.append( years ).append( "y " );
}
if ( days != 0 ) {
    sb.append( days ).append( "d " );
}
if ( hours != 0 ) {
    sb.append( hours ).append( "h " );
}
if ( minutes != 0 ) {
    sb.append( minutes ).append( "m " );
}
sb.append( " ago" );

完整的方法将是:

public String getLastgame() {

    long time = ((System.currentTimeMillis() / 60000) - this.config.getLastgameTime());

    long oneYear = 60 * 24 * 365;
    long oneDay = 60 * 24;
    long oneHour = 60;

    // extract years
    int years = time / oneYear;
    // update your time
    time = time % oneYear;

    // extract days
    long days = time / oneDay;
    // update your time
    time = time % oneDay;

    // extract hours    
    long hours = time / oneHour;

    // extract minutes (the remaining)
    minutes = time % oneHour;

    StringBuilder sb = new StringBuilder( "Last time " );
    if ( years != 0 ) {
        sb.append( years ).append( "y " );
    }
    if ( days != 0 ) {
        sb.append( days ).append( "d " );
    }
    if ( hours != 0 ) {
        sb.append( hours ).append( "h " );
    }
    if ( minutes != 0 ) {
        sb.append( minutes ).append( "m " );
    }
    sb.append( " ago" );

    return sb.toString();

}
于 2013-05-25T16:28:40.680 回答
0

获取字符串中'd'、'm'和'h'的索引。检查索引 -1 和索引 2 处字符的值。如果索引 -2 是空格,请检查索引 1。如果是 0,则删除这些索引。这是一种方法。

于 2013-05-25T16:20:35.547 回答