Sponsored Ad

Wednesday, March 31, 2010

Convert Given Time to HH:MM:SS Format in C#

This post will guide you to convert Given H:M:S time format to HH:MM:SS format. The given method you can  also use for your custom format or if you can Hour , Minute and Seconds in different variables and you want to combine it in HH:MM:SS format.

 

       /// <summary>
       /// Purpose : to bring the time in HH:MM:SS format for a given string in H:M:S format
       /// <para>for example, if the time is sent as 8:3:5 then it will be converted to 08:03:05</para>
       /// <para>IN parameter: string time, bool showhour, showminute, showsecond</para>
       /// RETURN value : string in the format HH:MM:SS
       /// </summary>
       public static string GetProperTimeValue(string pTime, bool pShowHour, bool pShowMinute, bool pShowSecond)
       {
           string returnTime = "";

           try
           {
               //STEP 1 : Removing the seconds
               string mHourMinute = pTime.Substring(0, pTime.LastIndexOf(":"));

               //STEP 2 : Extracting hour, minute, seconds values
               string mHour = mHourMinute.Substring(0, mHourMinute.IndexOf(":"));
               string mMinute = mHourMinute.Substring(mHourMinute.LastIndexOf(":") + 1);
               string mSeconds = pTime.Substring(pTime.LastIndexOf(":") + 1);

               //STEP 3 : If the length of hour / minute is 1 then prefix with 0
               mHour = (mHour.Length == 1 ? "0" + mHour : mHour);
               mMinute = (mMinute.Length == 1 ? "0" + mMinute : mMinute);
               mSeconds = (mSeconds.Length == 1 ? "0" + mSeconds : mSeconds);

               returnTime = (pShowHour ? mHour + (pShowMinute ? ":" : "") : "") +
                   (pShowMinute ? mMinute + (pShowSecond ? ":" : "") : "") +
                            (pShowSecond ? mSeconds : "");
           }
           catch
           {
               returnTime = pTime;
           }

           return returnTime.Trim();
       }

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers