Friday, May 31, 2013

Pretty Date & Time representations in Java


Date and time representations in java has never been easy as both the Date as well as Calendar APIs have been poorly designed. In contrast, ActiveSupport gem in ruby allows for time to be declared constructively. For example, the time can either have arithmetic operations like 45.minutes + 2.months or can call constructive operations such as 1.year.from_now .
In java, this is not the case but thanks to PrettyTime library, this is possible from java as well. This is an easy-to use library which can be used easily without much of a fuss.
Apart from simple time substitutions, Pretty time can also pick up values within the String.

Consider the following example:
"I did this work three days ago"
"and I did that one week ago"


when processed by the following code,

List parse = new PrettyTimeParser().parse("I did this work three days ago");
parse.addAll(new PrettyTimeParser().parse("and I did that one week ago"));
for(Date dt : parse)
System.out.println("date obtained: "+dt);

results in :
date obtained: Tue May 28 18:46:00 IST 2013
date obtained: Fri May 24 18:46:00 IST 2013


There are various use cases that are still to be covered and working on them looks promising. I am giving this a try on a fork of the same project. I am hoping for some constructive feedback and a productive outcome from this exercise.

No comments: