Home >Java >javaTutorial >How to Display \'Time Ago\' in Java?

How to Display \'Time Ago\' in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 11:00:11133browse

How to Display

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn