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

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

    for correct strings ("1hour, 3sec", "3 min" but not "0 hour, 0 min, 3 sec") i write this code:

    int seconds = (int)(millis / 1000) % 60 ;
    int minutes = (int)((millis / (1000*60)) % 60);
    int hours = (int)((millis / (1000*60*60)) % 24);
    int days = (int)((millis / (1000*60*60*24)) % 365);
    int years = (int)(millis / 1000*60*60*24*365);
    
    ArrayList timeArray = new ArrayList();
    
    if(years > 0)   
        timeArray.add(String.valueOf(years)   + "y");
    
    if(days > 0)    
        timeArray.add(String.valueOf(days) + "d");
    
    if(hours>0)   
        timeArray.add(String.valueOf(hours) + "h");
    
    if(minutes>0) 
        timeArray.add(String.valueOf(minutes) + "min");
    
    if(seconds>0) 
        timeArray.add(String.valueOf(seconds) + "sec");
    
    String time = "";
    for (int i = 0; i < timeArray.size(); i++) 
    {
        time = time + timeArray.get(i);
        if (i != timeArray.size() - 1)
            time = time + ", ";
    }
    
    if (time == "")
      time = "0 sec";
    

提交回复
热议问题