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

后端 未结 27 1813
夕颜
夕颜 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:29

    If you know the time difference would be less than an hour, then you can use following code:

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
    
        c2.add(Calendar.MINUTE, 51);
    
        long diff = c2.getTimeInMillis() - c1.getTimeInMillis();
    
        c2.set(Calendar.MINUTE, 0);
        c2.set(Calendar.HOUR, 0);
        c2.set(Calendar.SECOND, 0);
    
        DateFormat df = new SimpleDateFormat("mm:ss");
        long diff1 = c2.getTimeInMillis() + diff;
        System.out.println(df.format(new Date(diff1)));
    

    It will result to: 51:00

提交回复
热议问题