Skip to content

Commit 20f64d4

Browse files
committed
Add non-relative duration format methods
1 parent 1861537 commit 20f64d4

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

‎core/src/main/java/org/ocpsoft/prettytime/PrettyTime.java‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,29 @@ public String format(final List<Duration> durations)
347347
return result;
348348
}
349349

350+
/**
351+
* Given a date, returns a non-relative format string for the
352+
* approximate duration of the difference between the date and now.
353+
*
354+
* @param date the date to be formatted
355+
* @return A formatted string of the approximate duration
356+
*/
357+
public String formatApproximateDuration(Date date) {
358+
Duration duration = approximateDuration(date);
359+
return formatDuration(duration);
360+
}
361+
362+
/**
363+
* Given a duration, returns a non-relative format string.
364+
*
365+
* @param duration the duration to be formatted
366+
* @return A formatted string of the duration
367+
*/
368+
public String formatDuration(Duration duration) {
369+
TimeFormat timeFormat = getFormat(duration.getUnit());
370+
return timeFormat.format(duration);
371+
}
372+
350373
/**
351374
* Get the registered {@link TimeFormat} for the given {@link TimeUnit} or null if none exists.
352375
*/

‎core/src/test/java/org/ocpsoft/prettytime/PrettyTimeTest.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,21 @@ public void testCalendarParameter() throws Exception
307307
c.add(Calendar.YEAR, -1);
308308
assertEquals("1 year ago", t.format(c));
309309
}
310+
311+
/**
312+
* Tests formatApproximateDuration and by proxy, formatDuration.
313+
*
314+
* @throws Exception
315+
*/
316+
@Test
317+
public void testFormatApproximateDuration() throws Exception
318+
{
319+
long tenMinMillis = java.util.concurrent.TimeUnit.MINUTES.toMillis(10);
320+
Date tenMinAgo = new Date(System.currentTimeMillis()-tenMinMillis);
321+
PrettyTime t = new PrettyTime();
322+
String result = t.formatApproximateDuration(tenMinAgo);
323+
assert result.equals("10 minutes");
324+
}
310325

311326
// Method tearDown() is called automatically after every test method
312327
@After

0 commit comments

Comments
 (0)