社交網站常常會顯示幾分鐘前,幾個小時前之類的時間,java裏頭有個prettyTime的類庫能夠用來作這樣的轉換,這裏介紹一下。java
<dependency> <groupId>org.ocpsoft.prettytime</groupId> <artifactId>prettytime</artifactId> <version>4.0.1.Final</version> </dependency>
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)));
輸出app
12 分鐘 後
public interface TimeFormat { String format(Duration var1); String formatUnrounded(Duration var1); String decorate(Duration var1, String var2); String decorateUnrounded(Duration var1, String var2); }
這裏有個decorate方法,去包裝格式化信息,好比org/ocpsoft/prettytime/format/SimpleTimeFormat的實現maven
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(); }