javadatetimedatediffrelative-time-span

How to calculate "time ago" in Java?


In Ruby on Rails, there is a feature that allows you to take any Date and print out how "long ago" it was.

For example:

8 minutes ago
8 hours ago
8 days ago
8 months ago
8 years ago

Is there an easy way to do this in Java?


Solution

  • Take a look at the PrettyTime library.

    It's quite simple to use:

    import org.ocpsoft.prettytime.PrettyTime;
    
    PrettyTime p = new PrettyTime();
    System.out.println(p.format(new Date()));
    // prints "moments ago"
    

    You can also pass in a locale for internationalized messages:

    PrettyTime p = new PrettyTime(new Locale("fr"));
    System.out.println(p.format(new Date()));
    // prints "à l'instant"
    

    As noted in the comments, Android has this functionality built into the android.text.format.DateUtils class.