Java漂亮的打印持续时间

Java漂亮的打印持续时间,java,timespan,pretty-print,Java,Timespan,Pretty Print,是否有Java类或一些示例代码可以将Java日期或时间戳转换为以下内容: "3 hours" " 20 seconds" "25 minutes" 我需要在我的web应用程序中使用这些字符串来显示生成一个文件所需的时间(当然是以非常漂亮的打印方式:) 谢谢,这听起来很像。您可以利用其中的代码来设置这样的持续时间格式。您可以从javaCalendar类中获取小时、分钟和秒,然后根据需要(小时、分钟…)对它们进行编码 Calendar c=Calendar.getInstance(); c、 s

是否有Java类或一些示例代码可以将Java日期或时间戳转换为以下内容:

"3 hours"
" 20 seconds"
 "25 minutes"
我需要在我的web应用程序中使用这些字符串来显示生成一个文件所需的时间(当然是以非常漂亮的打印方式:)


谢谢,

这听起来很像。您可以利用其中的代码来设置这样的持续时间格式。

您可以从java
Calendar
类中获取小时、分钟和秒,然后根据需要(小时、分钟…)对它们进行编码

Calendar c=Calendar.getInstance();
c、 setTimeinMillis();
整小时=c.get(日历小时);
int mins=c.get(Calendar.MIN);
...
带有:


另外,很容易获得两个时间点之间的小时/秒/分钟数。

尝试使用SimpleDataFormat:

使用JodaTime是最好的总体方法,但这里有一种方法可以在不使用任何特定于域的库的情况下,在


当然,您可以将其扩展到包括天/月/年/等。

使用正确的
时区
,这是可行的:
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);
...
PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );
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();
}
    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