user7274707
user7274707

Reputation: 9

Convert Hours,mins and secs into HH:MM:SS format

I have a time class that has functions to compute hours, mins and secs individually .I want to convert the calculated time(which is of format 1h 30min 20secs obtained from toReadableString() method in the code below) into HH;MM:SS format. I have seen some examples but that doesn't solve my problem.Also, I want to calculate total time duration by adding two different time slots(for eg.1st time slot is 20mins 45secs and 2nd time slot is 1hr30mins15secs which adds together to give 1hr51mins).Any help is appreciated.Thanks in advance.

   public int getMinutes()
    {
        long minutesTotal = (time / 1000 / 60);

        return (int)minutesTotal % 60;
    }


   public int getSeconds()
    {
        return (int)(time - (getHours() * 60 * 60 * 1000) - (getMinutes() * 60 * 1000)) / 1000;
    }

    public int getHours()
    {
        return (int)(time / 1000 / 60 / 60);
    }
   public String toString()
    {
        return "abs_" + Convert.ToString(time);
    }

    /**
    * Convert time to a human readable string.
    * @return - human readable string.
    */
    public String toReadableString()
    {
        if (getHours() == 0 && getMinutes() == 0 && getSeconds() == 0)
        {
            if (getTime() > 0)
            {
                return getTime() + "ms";
            }
            else
            {
                return "zero";
            }
        }

        String result = "";
        if (getHours() != 0)
        {
            result += Convert.ToString(getHours()) + "h ";
        }
        else
        {
            if (getMinutes() == 0)
            {
                return Convert.ToString(getSeconds()) + "sec";
            }
        }
        result += Convert.ToString(getMinutes()) + "m ";
        result += Convert.ToString(getSeconds()) + "s";
        return result;
    }

Upvotes: 0

Views: 1331

Answers (1)

Tony
Tony

Reputation: 17637

In C# you can use TimeSpan to do Math on these time values.

Try this:

 var first = new TimeSpan(0, 20, 45);    // 20mins 45secs 
 var second = new TimeSpan(1, 30, 15);   // 2nd time slot is 1hr30mins15secs
 var result = first + second;

 Debug.WriteLine(result.ToString());

.

 public String toReadableString(TimeSpan ts)
 {
     // TODO: Write your function that receives a TimeSpan and generates the desired output string formatted...
     return ts.ToString();    // 01:51:00
 }

Upvotes: 2

Related Questions