Monday, November 19, 2012

PrettyTime and Joda playing nice

PrettyTime is a library for printing elapsed times such as "2 hours ago". Joda is the library to replace JDK's ancient and problematic package.

Unfortunately, PrettyTime uses JDK's date class only, and doesn't welcome Joda classes such as LocalDateTime to be passed in directly. Also, it does not support time zones yet (apparently that's low priority).

Because of its great i18n support (lots of translations) I live with this handicap, and convert:

    LocalDateTime now =;

    //store this instant to db:
    long time = now.toDate().getTime();

    //then load it from db again:
    LocalDateTime nowAgain = new LocalDateTime(time);
    assert now.equals(nowAgain);

    //wrong: printing this is off by the local time zone difference to UTC:
    System.out.println(new PrettyTime().format(nowAgain.toDate()));

    //correctly adjusted:
    Date javaUtilDate = nowAgain.toDateTime(DateTimeZone.UTC).toDate();
    System.out.println(new PrettyTime().format(javaUtilDate));
This prints "moments ago". Phew! Time for beer.

No comments:

Post a Comment