Working with duration

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of GJ GJ 1 year, 10 months ago.

  • Author
    Posts
  • #22459
    Profile photo of GJ
    GJ
    Participant

    Hello Guys,

    Is there a direct way to handle the "duration" in powershell. For example, I have the below three duration and I would like to add them and get the result as a timespan object so that I can get the totalminutes or totalseconds etc.

    
    PS [15:48:55] D:\> $a = "1:02:48" #hh:mm:ss
    
    PS [15:48:57] D:\> $b = "21:38" #mm:ss
    
    PS [15:49:01] D:\> $c = "44:21" #mm:ss
    
    
  • #22460
    Profile photo of Don Jones
    Don Jones
    Keymaster

    .NET has a "Timespan" object that represents a duration of time, and you can do math with them. See https://msdn.microsoft.com/en-us/library/system.timespan(v=vs.110).aspx. There's a static Parse() method that will accept a variety of string formats and return a Timespan object.

    $ts = System.TimeSpan::Parse('hh:mm:ss')

    That's off the top of my head, so it might not be 100% accurate, but that's the idea.

    Once you have a Timespan, you can add or subtract others. A ToString() method of the Timespan lets you turn the Timespan into a readable string format.

  • #22461
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Well, your $a, $b and $c variables are currently strings. You would need to have Timespan objects first, at which point they can simply be added together with the + operator. Whether you need to convert strings into timespans or just start with a timespan depends on what you're doing; I'll show examples of both here:

    # Converting from strings.  Note that the colon character is escaped with a backslash in the patterns.
    # Casting to [string[]] is necessary here to make sure the right overload of TimeSpan.ParseExact gets called.
    
    [string[]] $patterns = @(
        'mm\:ss'
        'h\:mm\:ss'
        'hh\:mm\:ss'
    )
    
    $a = [timespan]::ParseExact('1:02:48', $patterns, [cultureinfo]::CurrentCulture)
    $b = [timespan]::ParseExact('21:38', $patterns, [cultureinfo]::CurrentCulture)
    $c = [timespan]::ParseExact('44:21', $patterns, [cultureinfo]::CurrentCulture)
    
    $total = $a + $b + $c
    $total
    
    # Using New-Timespan instead of bothering with strings.  Less fragile and less annoying.  🙂
    
    $a = New-TimeSpan -Hours 1 -Minutes 2 -Seconds 48
    $b = New-TimeSpan -Minutes 21 -Seconds 38
    $c = New-TimeSpan -Minutes 44 -Seconds 21
    
    $total = $a + $b + $c
    $total
    
  • #22464
    Profile photo of GJ
    GJ
    Participant

    Thank you Dave & Don.

You must be logged in to reply to this topic.