Reputation: 87
I have two durations in my code. And I want to add them to get the total duration.
Many code examples add some durations to a date, but I have here two durations.
$startOfAnalysis = $(Get-Date)
#Analysis code here
$analysisDuration = $(Get-Date) - $startOfAnalysis
$totalAnalysisTime = "{0:HH:mm:ss}" -f ([datetime] $analysisDuration.Ticks)
$totalAnalysisTime #Outputs similar to 00:16:21
$startOfExecution = $(Get-Date)
#Execution code here
$executionDuration = $(Get-Date) - $startOfExecution
$totalExecutionTime = "{0:HH:mm:ss}" -f ([datetime]$executionDuration.Ticks)
$totalExecutionTime #Outputs similar to 00:13:39
#($totalAnalysisTime+$totalExecutionTime) How to add the two to get 00:30:00?
How do I sum it up to make it to 30 minutes, i. e. 00:30:00?
Upvotes: 1
Views: 1374
Reputation: 175085
You can add two TimeSpan
instances together directly, no need for conversion to DateTime
and back:
$total = $executionDuration + $analysisDuration
Just like with a DateTime
instance, you can now use the -f
string format operator, but beware that you need to escape special characters:
'{0:hh\:mm\:ss}' -f $total
Upvotes: 1
Reputation: 2434
I think there are two options.
First one: Convert your time back to seconds and then sum them up. Like that:
$Time1 = "01:56:40"
$textReformat1 = $Time1 -replace ",","."
$Time2 = "01:56:40"
$textReformat2 = $Time2 -replace ",","."
$seconds = ([TimeSpan]::Parse($textReformat1)).TotalSeconds + ([TimeSpan]::Parse($textReformat2)).TotalSeconds
$TimeSpan = [timespan]::fromseconds($seconds)
("{0:HH\:mm\:ss}" -f [DateTime]$TimeSpan.Ticks)
And option two (the simple one):
Just calculate everything together before you convert them to a string. Something like that:
("{0:HH\:mm\:ss}" -f ([datetime]$analysisDuration.Ticks + $executionDuration.Ticks))
Credits to: Convert seconds to hh:mm:ss,fff format in PowerShell
For the example how to convert the timespan back to seconds
Upvotes: 1