How to convert Milliseconds to “X mins, x seconds” in Java?

后端 未结 27 1838
夕颜
夕颜 2020-11-22 03:59

I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current Syste

27条回答
  •  死守一世寂寞
    2020-11-22 04:16

    I have covered this in another answer but you can do:

    public static Map computeDiff(Date date1, Date date2) {
        long diffInMillies = date2.getTime() - date1.getTime();
        List units = new ArrayList(EnumSet.allOf(TimeUnit.class));
        Collections.reverse(units);
        Map result = new LinkedHashMap();
        long milliesRest = diffInMillies;
        for ( TimeUnit unit : units ) {
            long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);
            long diffInMilliesForUnit = unit.toMillis(diff);
            milliesRest = milliesRest - diffInMilliesForUnit;
            result.put(unit,diff);
        }
        return result;
    }
    

    The output is something like Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0}, with the units ordered.

    It's up to you to figure out how to internationalize this data according to the target locale.

提交回复
热议问题