Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 1.8 time functionality

So Java 1.8 comes with a whole new (and old) bunch of classes to manage time calculations: java.time.Instant, java.time.LocalTime, java.time.temporal.ChronoUnit, and maybe more...

But why is there no simple way to calculate the time difference between any of these? I would expect "time_later - time_earlier" to be the most used manipulation of time, but this is nowhere to be seen. I cannot subtract one LocalTime from the other and get a new LocalTime; I cannot subtract one Instant from the other to get a new Instant. Instead I have to fiddle with ChronoUnits.between, and long milliseconds and whatnots to achieve this very useful thing.

Why is this? There has to be something going on that I do not get? Or I'm just daft...?

like image 699
OppfinnarJocke Avatar asked Dec 04 '25 01:12

OppfinnarJocke


1 Answers

Before Java 8, the usual answer to your question was "use Joda Time"

  • http://joda-time.sourceforge.net/faq.html

But the author of Joda Time (Stephen Colebourne) was deeply involved in the new Java 8 time classes and methods. Here are two very good articles:

  • http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html

For your specific question, you might want to consider Java 8 "Duration" and "LocalTime", "LocalDate" and/or "LocalTimeDate" (among other options):

// A duration of 3 seconds and 5 nanoseconds
Duration duration = Duration.ofSeconds(3, 5);
Duration oneDay = Duration.between(today, yesterday);

// Tomorrow
LocalDate tomorrow = LocalDate.now().plusDays(1);

// Yesterday
LocalDate yesterday = LocalDate.now().plusDays(-1);

// before 5 houres and 30 minutes
LocalDateTime dateTime = LocalDateTime.now().minusHours(5).minusMinutes(30);
like image 139
paulsm4 Avatar answered Dec 05 '25 14:12

paulsm4



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!