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'
As I understand your problem, the "Human Time" class is a solution.
check Date Formatting and Parsing for Humans in Java with HumanTime .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With