Long converting to wrong time

Dan :

I am trying to format a long until days, hours, minutes, seconds and found a method online.

public static String getTime(long time) {
    long enlapsed = System.currentTimeMillis() - time;
    long days = TimeUnit.MILLISECONDS.toDays(enlapsed);
    enlapsed -= TimeUnit.DAYS.toMillis(days);

    long hours = TimeUnit.MILLISECONDS.toHours(enlapsed);
    enlapsed -= TimeUnit.HOURS.toMillis(hours);

    long minutes = TimeUnit.MILLISECONDS.toMinutes(enlapsed);
    enlapsed -= TimeUnit.MINUTES.toMillis(minutes);

    long seconds = TimeUnit.MILLISECONDS.toSeconds(enlapsed);

    String result = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
    return result.replace("0d ", "").replace("0h ", "").replace("0m ", "").replace("0s ", "");
}

and it was working but now suddenly inputting 4380 is giving 18151d 15h 33m 34s. What did I do wrong?

Sweeper :

The method you found online calculates how much time has elapsed between now, and a given timestamp. You can test that this method works going to a site like this, and multiplying the timestamp by 1000 to convert it to milliseconds, and passing that long to getTime.

The timestamp 4380 represents 4380ms after the Java Epoch, which is approximately 1 January 1970, which is about 18000 days ago.

If you want a more recent example, the timestamp 1568312340000 is just a few minutes before I started writing this, and doing System.out.println(getTime(1568312340000L)); gives a smaller duration.

What you seem to want is not to calculate the elapsed time between now and a certain timestamp. You seem to just want to convert an amount of milliseconds to a duration expressed in days, hours, minutes and seconds.

The method works by first calculating the difference in milliseconds between now and the given timestamp, putting the difference into a variable called enlapsed (spelling mistake!) Then it calculates how many days, hours, minutes and seconds goes into enlapsed milliseconds. What you want is everything this method does except the first part where it calculates the difference, so you should delete this line:

long enlapsed = System.currentTimeMillis() - time;

and replace it with:

long enlapsed = time;

because you just want it to directly calculate what duration the time parameter represents.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=165606&siteId=1