Jump to Real's How-to Main page

Format a duration in ms into a string as "Days,Hours,minutes and seconds"

public class TimeUtils {

  public final static long ONE_SECOND = 1000;
  public final static long ONE_MINUTE = ONE_SECOND * 60;
  public final static long ONE_HOUR   = ONE_MINUTE * 60;
  public final static long ONE_DAY    = ONE_HOUR * 24;

  private TimeUtils() { }

  /**
  * converts time (in milliseconds) to
  *  "<w> days, <x> hours, <y> minutes and (z) seconds"
  */
  public static String millisecondToDHMS(long duration) {
    String res = "";
    long temp = 0;
    if (duration >= ONE_SECOND) {
       temp = duration / ONE_DAY;
       if (temp > 0) {
         res = temp + " day";
         if (temp > 1) {
            res += "s";
         }
         duration -= temp * ONE_DAY;

         if (duration >= ONE_MINUTE) {
            res += ", ";
         }
       }

       temp = duration / ONE_HOUR;
       if (temp > 0) {
          res += temp + " hour";
          if (temp > 1) {
             res += "s";
          }
          duration -= temp * ONE_HOUR;
          if (duration >= ONE_MINUTE) {
             res += ", ";
          }
       }

       temp = duration / ONE_MINUTE;
       if (temp > 0) {
          res += temp + " minute";
          if (temp > 1) {
              res += "s";
          }
          duration -= temp * ONE_MINUTE;

          if(duration >= ONE_SECOND) {
              res += " and ";
          }
       }

       temp = duration / ONE_SECOND;
       if (temp > 0) {
          res += temp + " second";
          if (temp > 1) {
              res += "s";
          }
       }
       return res;
    }
    else {
       return "0 second";
    }
  }

  public static void main (String args []) {
    System.out.println(millisecondToDHMS(123));
    System.out.println(millisecondToDHMS((5* ONE_SECOND) + 123));
    System.out.println(millisecondToDHMS(ONE_DAY + ONE_HOUR));
    System.out.println(millisecondToDHMS
      (ONE_DAY + ONE_HOUR + (2 * ONE_MINUTE)));
    System.out.println(millisecondToDHMS
      ((4*ONE_DAY) + (3*ONE_HOUR) + (2 * ONE_MINUTE) + ONE_SECOND));
    System.out.println(millisecondToDHMS
      ((5*ONE_DAY) + (4*ONE_HOUR) + ONE_MINUTE + (2 * ONE_SECOND) + 123));
    /*
      output :
         0 second
         5 seconds
         1 day, 1 hour
         1 day, 1 hour, 2 minutes
         4 days, 3 hours, 2 minutes and 1 second
         5 days, 4 hours, 1 minute and 2 seconds
    */
  }
}

If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2007
[ home ]