【发布时间】:2011-04-05 00:46:21
【问题描述】:
是否有 Java 类或一些示例代码可以将 Java 日期或时间戳转换为:
"3 hours"
" 20 seconds"
"25 minutes"
我需要在我的网络应用程序中使用这些字符串来显示生成一个文件需要多少时间(当然是以漂亮的打印方式:))
谢谢,
【问题讨论】:
标签: java timespan pretty-print
是否有 Java 类或一些示例代码可以将 Java 日期或时间戳转换为:
"3 hours"
" 20 seconds"
"25 minutes"
我需要在我的网络应用程序中使用这些字符串来显示生成一个文件需要多少时间(当然是以漂亮的打印方式:))
谢谢,
【问题讨论】:
标签: java timespan pretty-print
与JodaTime:
PeriodFormat.getDefault( ).print( Hours.THREE );
PeriodFormat.getDefault( ).print( Seconds.seconds( 25 ) );
PeriodFormat.getDefault( ).print( Minutes.minutes( 20 ) );
附:也很容易获得两个时间点之间的小时/秒/分钟数。
【讨论】:
使用 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();
}
现在你可以拥有 (as seen on 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
您当然可以将其扩展到包括天/月/年/等。
【讨论】:
您可以从 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);
...
【讨论】:
这听起来很像TimeAgo。您也许可以利用其中的代码来格式化这样的持续时间。
【讨论】:
尝试使用 SimpleDateFormat: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
【讨论】:
TimeZone,可行:stackoverflow.com/questions/2705674