Java: date and time relative to the current (server) time

We use MySQL to store some dates. I want to show them as relative time periods in the user interface: 2 hours ago, 3 days ago, etc. (E.g. Twitter for updates)

Is there a known way to achieve this, or do I need to be creative with it?

To be clear, I want to convert: 07/27/2009 12:20 → '2 days ago'

+3
source share
8 answers

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

check Date formatting and analysis for people in Java using HumanTime .

+4
source

Joda . , Joda Duration, Period, :

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.
+2

API Java - Calendar.add() ( ).

+2

, timestamps unix ( , Java ), .

time = now - then;
time /= 1000; /* if milliseconds... */
seconds = time % 60; time /= 60;
minutes = time % 60; time /= 60;
hours   = time % 60; time /= 60;
days    = time % 24; time /= 24;
weeks   = time % 7; time /= 7;

(, ...) .

.

+1

: UTC, JodaTime, .

, , , DSL, , .., , .

+1

.

Java, API JodaTime Date,

3 :

DateTime date = new DateTime();
DateTime threeDA = date.plusDays(-3);
int daysBetween = Days.daysBetween(dbDate, threeDA).getDays();
int monthsBetween = Months.monthsBetween(dbDate, threeDA).getMonths();

JodaTime Period/Duration.

MySQL MySQL, :

SELECT SUBTIME(SYSDATE(),'3'); -- untested, no MySQL to hand
SELECT SUBTIME('2007-12-31 23:59:59.999999','3 0:0:0.000000');

:

SELECT DATEDIFF(columnname, SYSDATE()); -- Days since
SELECT TIMEDIFF(columnname, SYSDATE()); -- Time since

Java, :

GregorianCalendar threeDA = new GregorianCalendar();
threeDA.add(GregorianCalendar.DAY_OF_YEAR, -3);
+1

java , Joda.

0

MySQL:

CONVERT('date-time-value-here', DATETIME) - NOW()
0

Source: https://habr.com/ru/post/1713751/


All Articles