Reputation: 2068
I have a TimeSpan that I want to round before adding it to my file.
Sometimes its ok like this: 12:03:55
but sometimes it is like this: 04:12:32.96472749
It should not look like this just give me the seconds so I thought of rounding it up or down it doesnt even matter.
I tried this: ([Math]::Round($result))
=> Where $result is the timespan but it is saying that the method is overloaded even though I saw it on StackOverflow like this...
also this does not work either: ([Math]::Round($result,2))
Maybe someone can help me because I think there is a special way to round TimeSpans and not normal decimals.
Edit:
I just checked out String Formatting like this:
$formattedTime = "{0:hh\:mm\:ss}" -f ([TimeSpan] $result)
It looks good but I need to add Days in front if the date goes over 24Hours .. so something like 'dd' maybe?
Ty Faded~
Upvotes: 1
Views: 2057
Reputation: 61068
You cannot format a TimeSpan object as if it were a DateTime object. For that, you need to put together your own format string and use the individual properties you need:
Without days:
$ts = [timespan]::new(0,12,3,55,964.72749)
('{0} {1:D2}:{2:D2}:{3:D2}' -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds).TrimStart("0 ")
# returns 12:03:55
With days (same format string)
$ts = [timespan]::new(11,12,3,55,964.72749)
('{0} {1:D2}:{2:D2}:{3:D2}' -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds).TrimStart("0 ")
# returns 11 12:03:55
The time properties of a TimeSpan object are ReadOnly, so you cannot set the Milliseconds to 0 unfortunately.
If you do want to get a 'rounded' TimeSpan object where the Milliseconds are stripped off, you can do this:
$ts = [timespan]::new(0,12,3,55,964.72749)
# create a new TimeSpan object from the properties, leaving out the MilliSeconds
$ts = [timespan]::new($ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds)
Upvotes: 1