Saturday, March 20, 2010

Formatting time with PrettyTime JSP Tag

In Web 2.0 applictions, timestamp is no longer displayed in the pattern "yyyy-MM-dd hh:mm:ss", such as 2010-03-20 13:38:20". Instead, it is formmated as so called "pretty time", such as "5 Minutes ago". In Java world, there is an open source library called PrettyTime to implement that.

PrettyTime is an OpenSource time formatting library. Completely customizable, PrettyTime creates human readable, relative timestamps like those seen on Digg, Twitter, and Facebook. It’s simple, get started “right now!”

To use PrettyTime in Java code, it's petty simple:
public String getPretty(Date date) {
  PrettyTime p = new PrettyTime();
  String prettier = p.format(date);
  return prettier;

 }

It is generally a good practice to render date prettier in display layer, that is, JSP file. Therefore, we will create a simple JSP Tag to make our date or time display in a fashion way. And the tag will implement in JSP Tag Files, which was introduced in JSP 2.0.

Preparation

Add PrettyTime in your project's building path, I use Maven:

 com.ocpsoft
 ocpsoft-pretty-time
 1.0.5


prettyTime.tag

This JSP Tag File will be placed at:
webapp/WEB-INF/tags/prettyTime.tag
This tag will require one Date attribute, the date you want to format. The prettyTime.tag as following:

<%@ tag import="com.ocpsoft.pretty.time.PrettyTime"  import="java.util.Date"%>
<%@ attribute name="date" required="true" type="java.util.Date" %>
 
<%
 PrettyTime p = new PrettyTime();
    String prettier = p.format(date);
 out.println(prettier);
%>


Usage in JSP file

It is very easy to use prettyTime tag in your JSP file. You need to declare our tag at first.
<%@ taglib prefix="kc" tagdir="/WEB-INF/tags"%>

Ordered:


3 comments:

MeMyselfAndI said...

This post is useless without the source for the tag class. Sorry.

Ke Cai said...

Hi dude,

I'm using tag file instead of tag class.....
So no class required.

Matt said...

Yeah, the code hasn't displayed properly, you have to view the page source to see all of it.