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

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

Linda Hamilton
Release: 2024-11-27 11:00:11
Original
194 people have browsed it

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"
Copy after login

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"
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template