Search code examples
powershellformattingtimespan

PowerShell New-TimeSpan Displayed Friendly with Day(s) Hour(s) Minute(s) Second(s)


I've been looking for a PowerShell script similar to examples found in .NET examples. To take a New-TimeSpan and display is at 1 day, 2 hours, 3 minutes, 4 seconds. Exclude where its zero, add plural "s" where needed. Anybody have that handy?

This is as far as I got:

$StartDate = (Get-Date).ToString("M/dd/yyyy h:mm:ss tt")

Write-Host "Start Time: $StartDate"

# Do Something

$EndDate = (Get-Date).ToString("M/dd/yyyy h:mm:ss tt")

Write-Host "End Time: $EndDate" -ForegroundColor Cyan

$Duration = New-TimeSpan -Start $StartDate -End $EndDate
$d = $Duration.Days; $h = $Duration.Hours; $m = $Duration.Minutes; $s = $Duration.Seconds

Write-Host "Duration: $d Days, $h Hours, $m Minutes, $s Seconds"

Solution

  • Why not doing it straight forward like this:

    $StartDate = (Get-Date).AddDays(-1).AddMinutes(-15).AddSeconds(-3)
    $EndDate = Get-Date
    
    $Duration = New-TimeSpan -Start $StartDate -End $EndDate
    
    $Day = switch ($Duration.Days) {
        0 { $null; break }
        1 { "{0} Day," -f $Duration.Days; break }
        Default {"{0} Days," -f $Duration.Days}
    }
    
    $Hour = switch ($Duration.Hours) {
        #0 { $null; break }
        1 { "{0} Hour," -f $Duration.Hours; break }
        Default { "{0} Hours," -f $Duration.Hours }
    }
    
    $Minute = switch ($Duration.Minutes) {
        #0 { $null; break }
        1 { "{0} Minute," -f $Duration.Minutes; break }
        Default { "{0} Minutes," -f $Duration.Minutes }
    }
    
    $Second = switch ($Duration.Seconds) {
        #0 { $null; break }
        1 { "{0} Second" -f $Duration.Seconds; break }
        Default { "{0} Seconds" -f $Duration.Seconds }
    }
    
    "Duration: $Day $Hour $Minute $Second"
    

    Output would be :

    Duration: 1 Day, 0 Hours, 15 Minutes, 3 Seconds
    

    With 2 in each part of the duration ...

    $StartDate = (Get-Date).AddDays(-2).AddHours(-2).AddMinutes(-2).AddSeconds(-2)
    

    the result would be this:

    Duration: 2 Days, 2 Hours, 2 Minutes, 2 Seconds
    

    Of course you should wrap this in a function if you need it more than once. ;-)
    And of course you can add more complex conditions if you like.