Momentjs calendar() equivalent for Java

PerrierCitror picture PerrierCitror · Oct 1, 2017 · Viewed 8.1k times · Source

Momentjs has the calendar() function to pretty print timespans like below.

For example:

"Last Monday at 1:14 PM"

"09/21/2017" (if the date is a while ago)

Is there an equivalent function in Java (Joda-Time if possible)?

moment().subtract(10, 'days').calendar(); // 09/21/2017
moment().subtract(6, 'days').calendar();  // Last Monday at 1:14 PM
moment().subtract(3, 'days').calendar();  // Last Thursday at 1:14 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 1:14 PM
moment().calendar();                      // Today at 1:14 PM
moment().add(1, 'days').calendar();       // Tomorrow at 1:14 PM
moment().add(3, 'days').calendar();       // Wednesday at 1:14 PM
moment().add(10, 'days').calendar();      // 10/11/2017

Answer

Basil Bourque picture Basil Bourque · Oct 1, 2017

java.time

Modern approach uses the industry-leading java.time classes.

ZoneId z = ZoneId.now( “America/Montreal”  ) ;
LocalDate today = LocalDate.now( z ) ;

Use the plus and minus methods to do math.

LocalDate tomorrow = today.plusDays( 1 ) ;

Search Stack Overflow. Nearly every basic date-time Question has already been asked an answered.

Strings

The java.time classes do not generate strings such as “tomorrow” and “Last Monday”. So no direct equivalent of your referenced library. You will have to do the peasant work yourself.

Search for the DateTimeFormatter class, and the DateTimeFormatterBuilder class.

Also, the DayOfWeek enum and its auto-localizing getDisplayName method may be useful.

prettytime

The prettytime library may help you, though I’ve not used it.

Joda-Time

The Joda-Time project is in maintenance mode. The team advises migration to the java.time classes.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.