November 14, 2015

Format date and time in java with prettytime

0  comments

Prettytime is a nice java library to format a java Date()s in a nice humanized ago format, like:

  • moments ago
  • 2 minutes ago
  • 13 hours ago
  • 7 months ago
  • 2 years ago

Prettytime is localized in over 30 languages.

It’s super simple to use

Add the dependency to your maven pom:


   org.ocpsoft.prettytime
   prettytime
   3.2.7.Final

or an sbt dependency if you use an activator project like play framework.

libraryDependencies += "org.ocpsoft.prettytime" % "prettytime" % "3.2.7.Final"

Then add the following static method to a helper class and call it from your json processor or your template engine.

public static String agoHumanized(final Date date, Locale locale){
   PrettyTime p = new PrettyTime(locale);
   return p.format(date);
}

Thats it!

You can find the code on github and the documentation on the ocpsoft page. Happy coding.


Tags

agohumanized, date format, Java, maven, prettytime, sbt


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked

Information about Data protection

This site uses Akismet to reduce spam. Learn how your comment data is processed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}