Home >Java >javaTutorial >How Can I Elegantly Calculate \'Time Ago\' in Java?

How Can I Elegantly Calculate \'Time Ago\' in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 00:23:10274browse

How Can I Elegantly Calculate

Calculating Time Ago in Java: An Elegant Option

Similar to Ruby on Rails, Java offers a sophisticated way to display the time elapsed since a specific date. This feature, commonly referred to as "time ago," provides a clear and concise indication of how much time has passed.

Enter the PrettyTime Library

The PrettyTime library is an ideal solution for this task in Java. With its user-friendly interface, calculating "time ago" becomes effortless.

Usage

Getting started with PrettyTime is a breeze:

  1. Import the library using import org.ocpsoft.prettytime.PrettyTime;.
  2. Create an instance of the PrettyTime class using PrettyTime p = new PrettyTime();.
  3. Use the format method to display the elapsed time relative to a given date, e.g., System.out.println(p.format(new Date()));.

Internationalization

PrettyTime also supports internationalization, allowing you to display "time ago" in different languages. Simply create a PrettyTime instance with a specific locale, e.g.:

PrettyTime p = new PrettyTime(new Locale("fr"));
System.out.println(p.format(new Date()));

Note for Android Users

Android users have the convenience of using the android.text.format.DateUtils class, which provides built-in functionality for calculating "time ago."

The above is the detailed content of How Can I Elegantly Calculate \'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