Home >Java >javaTutorial >How to Display \'Time Ago\' in Java?
How to Calculate "Time Ago" in Java
Ruby on Rails provides a convenient feature for displaying the "time ago" for a given date. Is there a similar solution available in Java?
Answer:
Yes, you can utilize the PrettyTime library to achieve this functionality in Java.
Usage:
The PrettyTime library is straightforward to use:
import org.ocpsoft.prettytime.PrettyTime; PrettyTime p = new PrettyTime(); System.out.println(p.format(new Date())); // prints "moments ago"
Locale Support:
You can specify a locale for internationalized messages:
PrettyTime p = new PrettyTime(new Locale("fr")); System.out.println(p.format(new Date())); // prints "à l'instant"
Additional Options:
For Android applications, the android.text.format.DateUtils class provides similar functionality:
import android.text.format.DateUtils; String timeAgo = DateUtils.getRelativeTimeSpanString(new Date().getTime(), new Date().getTime(), DateUtils.MINUTE_IN_MILLIS).toString(); // prints "moments ago"
The above is the detailed content of How to Display \'Time Ago\' in Java?. For more information, please follow other related articles on the PHP Chinese website!