Home >Java >javaTutorial >How to Calculate \'Time Ago\' in Java?
How to Calculate Time Ago in Java
In Java, calculating "time ago" can be achieved using libraries or leveraging built-in Android methods.
PrettyTime Library
A popular library for generating time ago strings is PrettyTime. It simplifies the process significantly:
import org.ocpsoft.prettytime.PrettyTime; PrettyTime p = new PrettyTime(); System.out.println(p.format(new Date()));
This will print the time ago from the current date, such as "moments ago" or "8 minutes ago." PrettyTime supports various locales for internationalization as well.
Android DateUtils
Android offers a built-in DateUtils class that handles time ago calculations specifically for Android applications:
import android.text.format.DateUtils; String formattedTimeAgo = DateUtils.getRelativeTimeSpanString(dateMillis, nowMillis, DateUtils.MINUTE_IN_MILLIS);
This calculates the time ago between the specified dateMillis and the current time nowMillis. It returns a formatted string using specified time intervals, such as "8 minutes ago" or "8 days ago."
The above is the detailed content of How to Calculate \'Time Ago\' in Java?. For more information, please follow other related articles on the PHP Chinese website!