TimeSpan Extensions to Multiply and Divide

Posted: 11/08/2012

I needed to divide and multiply the value of a TimeSpan for a project I’m currently working on. The TimeSpan in .Net is a structure that doesn’t have operators associated with it. The easiest reusable method that I could think of was creating an extension method that would handle dividing or multiplying the the “Ticks” value of the TimeSpan and then returning a new TimeSpan based on that. Below is the Module. Depending on your project, you may need to import System.ComponentModel at the top of this file. Also, this should be “Portable Class Library” safe.

VB.Net


    Module TimeSpanExtensions

        '*********************************************************************************************************************
        '
        '            Module:  TimeSpanExtensions
        '      Organization:  http://www.blakepell.com        
        '      Initial Date:  10/18/2012
        '      Last Updated:  11/08/2012
        '     Programmer(s):  Blake Pell, blakepell@hotmail.com
        '
        '*********************************************************************************************************************

        ''' <summary>
        ''' Diplays a formatted vertical string with line breaks that contains the contents of the current TimeSpan
        ''' in a human readable form.
        ''' </summary>
        ''' <param name="ts"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function ToVerticalString(ts As TimeSpan) As String
            Dim sb As New StringBuilder
            sb.AppendFormat("{0} Days{1}", ts.Days, vbCrLf)
            sb.AppendFormat("{0} Hours{1}", ts.Hours, vbCrLf)
            sb.AppendFormat("{0} Minutes{1}", ts.Minutes, vbCrLf)
            sb.AppendFormat("{0} Seconds{1}", ts.Seconds, vbCrLf)
            sb.AppendFormat("{0} Milliseconds{1}", ts.Milliseconds, vbCrLf)            
            Return sb.ToString
        End Function

        ''' <summary>
        ''' Multiplies the TimeSpan by the provided value.
        ''' </summary>
        ''' <param name="ts"></param>
        ''' <param name="value"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function Multiply(ts As TimeSpan, value As Double) As TimeSpan
            Return New TimeSpan(ts.Ticks * value)
        End Function

        ''' <summary>
        ''' Divides the TimeSpan by the provided value.
        ''' </summary>
        ''' <param name="ts"></param>
        ''' <param name="value"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function Divide(ts As TimeSpan, value As Double) As TimeSpan
            Return New TimeSpan(ts.Ticks / value)
        End Function

    End Module