Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: date & time relative to current (server) time

We're using MySQL to store some dates. I'm looking to show these as relative time periods in the user interface: 2 hours ago, 3 days ago etc. (Like Twitter does for the updates for example)

Is there a well-known way to accomplish this, or should I get creative with it?

Just to be clear, I want to transform: 07/26/2009 12:20 -> '2 days ago'

like image 786
Dan Burzo Avatar asked May 31 '26 13:05

Dan Burzo


2 Answers

As I understand your problem, the "Human Time" class is a solution.

check Date Formatting and Parsing for Humans in Java with HumanTime .

like image 185
fg. Avatar answered Jun 03 '26 03:06

fg.


I would take a look at the Joda library for performing this type of date-time arithmetic. For example, you could create a Joda Duration and then convert it to a Period, giving you access to numerous useful methods:

ResultSet rs = ...
Date dbDate = rs.getDate("Date"); // Get stored time in database.
long serverTime = System.currentTimeMillis(); // Get current server time.

// Compute absolute difference between two time-stamps.
Duration duration = new Duration(Math.abs(serverTime - dbDate.getTime()));

// Convert to period and make use of getHours(), getMinutes(), etc for display purposes.
Period period = duration.toPeriod();

System.err.println("Hours: " + period.getHours());
System.err.println("Minutes: " + period.getMinutes()); // etc.
like image 27
Adamski Avatar answered Jun 03 '26 02:06

Adamski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!