How can I calculate a time span in Java and format the output?

Viewed 75812

I want to take two times (in seconds since epoch) and show the difference between the two in formats like:

  • 2 minutes
  • 1 hour, 15 minutes
  • 3 hours, 9 minutes
  • 1 minute ago
  • 1 hour, 2 minutes ago

How can I accomplish this??

18 Answers
    Date start = new Date(1167627600000L); // JANUARY_1_2007
    Date end = new Date(1175400000000L); // APRIL_1_2007


    long diffInSeconds = (end.getTime() - start.getTime()) / 1000;

    long diff[] = new long[] { 0, 0, 0, 0 };
    /* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
    /* min */diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
    /* hours */diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
    /* days */diff[0] = (diffInSeconds = (diffInSeconds / 24));

    System.out.println(String.format(
        "%d day%s, %d hour%s, %d minute%s, %d second%s ago",
        diff[0],
        diff[0] > 1 ? "s" : "",
        diff[1],
        diff[1] > 1 ? "s" : "",
        diff[2],
        diff[2] > 1 ? "s" : "",
        diff[3],
        diff[3] > 1 ? "s" : ""));

I'm not an expert in Java, but you can do t1-t2=t3(in seconds) then divide that by 60, would give you minutes, by another 60 would give you seconds. Then it's just a matter of figuring out how many divisions you need.

Hope it helps.

If your time-spans cross daylight-saving (summer-time) boundaries, do you want to report the number of days?

For example, 23:00 to 23:00 the next day is always a day but may be 23, 24 or 25 hours depending on whether the you cross a daylight-savings transition.

If you care about that, make sure you factor it into your choice.

You can use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenient methods were introduced.

Demo:

import java.time.Duration;
import java.time.Instant;

class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getFormattedDuration(1619575035, 1619810961));
    }

    public static String getFormattedDuration(long start, long end) {
        Instant startInstant = Instant.ofEpochSecond(start);
        Instant endInstant = Instant.ofEpochSecond(end);

        Duration duration = Duration.between(startInstant, endInstant);

        // Custom format
        // ####################################Java-8####################################
        return String.format("%d days, %d hours, %d minutes, %d seconds", duration.toDays(), duration.toHours() % 24,
                duration.toMinutes() % 60, duration.toSeconds() % 60);
        // ##############################################################################

        // ####################################Java-9####################################
        // return String.format("%d days, %d hours, %d minutes, %d seconds",
        // duration.toDaysPart(), duration.toHoursPart(),
        // duration.toMinutesPart(), duration.toSecondsPart());
        // ##############################################################################
    }
}

Output:

2 days, 17 hours, 32 minutes, 6 seconds

I always start with Joda Time. Working with dates and times in Java is always "fun" but Joda Time takes the strain off.

They have Interval and Duration classes which do half of what you are looking for. Not sure if they have a function for outputing in readable format though. I'll keep looking.

HTH

The Calendar class can handle most date related math. You will have to get the result of compareTo and output the format yourself though. There isn't a standard library that does exactly what you're looking for, though there might be a 3rd party library that does.

OK, after a brief peruse of the API it seems that you could do the following: -

  1. create some ReadableInstants representing start time and end time.
  2. Use Hours.hoursBetween to get the number of hours
  3. use Minutes.minutesBetween to get the number of minutes
  4. use mod 60 on the minutes to get the remaining minutes
  5. et voila!

HTH

This question is old and already has an answer but i have a better solution. Use relativeSpan from date utils

                dateHere.setText(DateUtils.getRelativeTimeSpanString(timeInMillis,
                        System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS));

it takes arguments: long/int time, current time and how you want it, _month,minute,second etc

long time1, time2;
time1 = System.currentMillis();

.. drink coffee

time2 = System.currentMillis();

long difference = time2 - time1 // millies between time1 and time2

java.util.Date differneceDate = new Date(difference);

To create a string like "2 Minutes" you should use DateFormatter/DateFormat. You can find more details on this in the the Java API spec (java.sun.com).

Related