Pretty Time – timestamp formatting made easy

It’s of the highest importance to present information in an understandable way. Users of applications shouldn’t waste their  valuable time figuring out the meaning of information. A great example is displaying date and time values to the user. Let’s assume you would like to show some operation took place just a couple of minutes ago, but you show: “2011-09-17 10:18” to the user. When users read this kind of information most of them won’t immediately realize it was just a couple of minutes ago. We will have to present the above date string into something like: “couple of minutes ago” and the user will instantly understand it.

Pretty formatting to present useful information

While working on the Android UI of a new application we wanted to achieve the above, therefore I made some quick research to find a library that supports pretty timestamp formatting. While googling (“pretty+time+in+java”) I found Pretty Time library and I gave it a try.

By means of Maven it is just a matter of seconds to include this into your project. The only thing you have to do is adding the  following dependency to the POM file:

[xml]
<dependency>
<groupId>com.ocpsoft</groupId>
<artifactId>ocpsoft-pretty-time</artifactId>
<version>1.0.7</version>
</dependency>
[/xml]

To format the date like nicely understandable information, one line of code does the job:

[java]
String prettyTimeString = new PrettyTime().format(new Date());
[/java]

The result is: “moments ago”.

Pretty Time works really pretty

Pretty Time is really easy to use, fully configurable and I18n support is included.

Just checkout the project page: http://ocpsoft.com/prettytime and enjoy the ease of timestamp formating!

If you wish to force formatting in English (default), you need to pass a locale object to the c-tor with the empty language value, like below. If you don’t do this you get the output in the language of the current locale settings.

[java]
String prettyTimeString = new PrettyTime(new Locale("")).format(new Date());
[/java]

I hope you will be able to make use of this nice library. Do you maybe know a different or even better one? What are your favorite libraries? Feel free to share them below!

This post has previously been posted on: blog.codeleak.pl

Tags:

Aspire Blog Team

Aspire Systems is a global technology services firm serving as a trusted technology partner for our customers. We work with some of the world's most innovative enterprises and independent software vendors, helping them leverage technology and outsourcing in our specific areas of expertise. Our services include Product Engineering, Enterprise Solutions, Independent Testing Services and IT Infrastructure Support services. Our core philosophy of "Attention. Always." communicates our belief in lavishing care and attention on our customers and employees.

3 comments

Comments are closed.