user5549921
user5549921

Reputation:

Get LocalTime from difference between two LocalTime's

I'm having issues finding an elegant way to subtract one LocalTime from another, but not by some amount of seconds, or minutes, but just this:

LocalTime difference = now - before;

Obviously this won't work, so in reality, what I'm after, is something that will take in two LocalTime's, and give me one back, so I can do the following:

00:01:42:519
00:02:13:217

00:00:30:698

I have tried the following:

long seconds = before.until(now, ChronoUnit.SECONDS);

But obviously that's only going to get me the seconds, ok, so I changed it to:

long millis = before.until(now, ChronoUnit.MILLIS);
long seconds = before.until(now, ChronoUnit.SECONDS);
long minutes = before.until(now, ChronoUnit.MINUTES);
long hours = before.until(now, ChronoUnit.HOURS);

But then I realised its just counting the entire time change in the specified unit, instead of just that units "contribution" to the change, if you understand what I mean.

PS: I've scanned SO for a few questions and they seem to be the same thing, only giving the entire difference back in a singular unit. If this is a duplicate, please point me in the right direction!

Any ideas?

Upvotes: 3

Views: 2944

Answers (3)

zlakad
zlakad

Reputation: 1384

    Instant start = Instant.now();
        //your lengthy code here
    Instant end = Instant.now();
    long nanoDiff = end.getNano() - start.getNano();

Why did I post this answer? B/c you can play with Instant class and get so many kinds of different format as an answer to your question...

Upvotes: 0

Ridcully
Ridcully

Reputation: 23655

Reading the JavaDoc of LocalTime#until(), I found this solution:

long differenceMillis = MILLIS.between(before, now);

Upvotes: 1

vandale
vandale

Reputation: 3650

This should do it:

LocalTime diff= t2.minusNanos(t1.toNanoOfDay());

https://ideone.com/3JB3U5

Upvotes: 3

Related Questions