Java美化输出时间段

5
有没有Java类或一些示例代码,可以将Java Date或Timestamp转换成类似于以下内容的东西:
"3 hours"
" 20 seconds"
 "25 minutes"

我需要在我的Web应用程序中使用这些字符串,以展示生成文件所需的时间(当然要以漂亮的方式呈现 :))

谢谢,

5个回答

8

使用JodaTime

PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );

另外,在两个时间点之间获取小时数/秒数/分钟数也非常容易。


3

使用JodaTime是最好的方法,但以下是一种不使用任何领域特定库的方法,间接地在MessageFormat的上下文中使用ChoiceFormat

static String choiceFor(int index, String noun) {
    return "{index,choice,0#|1#1 noun |1<{index,number,integer} nouns }"
        .replace("index", String.valueOf(index))
        .replace("noun", noun);
}
static String prettyPrint(int h, int m, int s) {
    String fmt = 
        choiceFor(0, "hour") +
        choiceFor(1, "minute") +
        choiceFor(2, "second");
    return java.text.MessageFormat.format(fmt, h, m, s).trim();
}

现在您可以拥有(如在ideone.com上所见):
    System.out.println(prettyPrint(1,2,3));
    // 1 hour 2 minutes 3 seconds

    System.out.println(prettyPrint(0,0,7));
    // 7 seconds

    System.out.println(prettyPrint(1,0,1));
    // 1 hour 1 second

    System.out.println(prettyPrint(0,2,0));
    // 2 minutes

当然,你可以将其扩展以包括天数/月份/年份等。

2

你可以从Java Calendar类中获取小时、分钟和秒,然后与任何你想要的内容连接起来(如小时、分钟……)。

Calendar c = Calendar.getInstance();
c.setTimeinMillis(<the time in milli second format (a long number)>);

int hours = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MIN);
...

1

这听起来非常像 TimeAgo。您可以利用其中的代码来格式化此类持续时间。


1

有了正确的TimeZone,这是可行的:http://stackoverflow.com/questions/2705674 - trashgod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接