序
社交網(wǎng)站經(jīng)常會(huì)顯示幾分鐘前池户,幾個(gè)小時(shí)前之類的時(shí)間,java里頭有個(gè)prettyTime的類庫可以用來做這樣的轉(zhuǎn)換,這里介紹一下氏涩。
maven
<dependency>
<groupId>org.ocpsoft.prettytime</groupId>
<artifactId>prettytime</artifactId>
<version>4.0.1.Final</version>
</dependency>
設(shè)置locale
Locale locale = Locale.CHINESE;
Locale.setDefault(Locale.CHINESE);
格式化
PrettyTime t = new PrettyTime(new Date(0));
System.out.println(t.format(new Date(1000 * 60 * 12)));
輸出
12 分鐘 后
源碼解析
TimeFormat
public interface TimeFormat {
String format(Duration var1);
String formatUnrounded(Duration var1);
String decorate(Duration var1, String var2);
String decorateUnrounded(Duration var1, String var2);
}
這里有個(gè)decorate方法蚁鳖,去包裝格式化信息磺芭,比如org/ocpsoft/prettytime/format/SimpleTimeFormat的實(shí)現(xiàn)
public String decorate(Duration duration, String time) {
StringBuilder result = new StringBuilder();
if(duration.isInPast()) {
result.append(this.pastPrefix).append(" ").append(time).append(" ").append(this.pastSuffix);
} else {
result.append(this.futurePrefix).append(" ").append(time).append(" ").append(this.futureSuffix);
}
return result.toString().replaceAll("\\s+", " ").trim();
}