Dutton

Custom format string for a .Net 3.5 TimeSpan object

Hmm, turns out TimeSpan only supports custom ToString formatting from .Net 4 onwards....

So here's a noddy extension method. Supports h for hours, m for minutes, s for seconds (along with hh for zero padding, and so on) and passes any other characters through to the output. It's all I needed but could be easily extended.

        /// <summary>
        /// Returns the TimeSpan object as a string using the provided format string.
        /// Currently supports:
        /// h  - Hours
        /// m  - Minutes
        /// s  - Seconds
        /// hh - Zero padded hours
        /// mm - Zero padded minutes
        /// ss - Zero padded seconds
        /// </summary>
        ///<param name="ts">The TimeSpan object</param>
        ///<param name="formatString">The format string</param>
        ///<returns>Formatted string representation of the TimeSpan</returns>
        public static string ToString(this TimeSpan ts, string formatString)
        {
            var sb = new StringBuilder();

            for (var i = 0; i < formatString.Length; i++)
            {
                switch (formatString[i])
                {
                    case 'h':
                        if (i < formatString.Length - 1 && formatString[i + 1] == 'h')
                        {
                            if (ts.Hours < 10) sb.AppendFormat("0{0}", ts.Hours);
                            else sb.Append(ts.Hours);
                            i++;
                        }
                        else sb.Append(ts.Hours);
                        break;
                    case 'm':
                        if (i < formatString.Length - 1 && formatString[i + 1] == 'm')
                        {
                            if (ts.Minutes < 10) sb.AppendFormat("0{0}", ts.Minutes);
                            else sb.Append(ts.Minutes);
                            i++;
                        }
                        else sb.Append(ts.Minutes);
                        break;
                    case 's':
                        if (i < formatString.Length - 1 && formatString[i + 1] == 's')
                        {
                            if (ts.Seconds < 10) sb.AppendFormat("0{0}", ts.Seconds);
                            else sb.Append(ts.Seconds);
                            i++;
                        }
                        else sb.Append(ts.Seconds);
                        break;
                    default: // Pass through any non recognised characters
                        sb.Append(formatString[i]);
                        break;
                }
            }
            return sb.ToString();
        }

Share this: