Powershell 如何舍入 TimeSpan?

Powershell How to round a TimeSpan?

我有一个 TimeSpan,我想在将它添加到我的文件之前对其进行舍入。

有时是这样的:12:03:55 但有时是这样的:04:12:32.96472749

它不应该看起来像这样只是给我几秒钟所以我想向上或向下四舍五入它甚至都没有关系。

我试过这个:([Math]::Round($result)) => 其中 $result 是时间跨度,但它说该方法已过载,即使我在 Whosebug 上看到它是这样的...

这也不起作用:([Math]::Round($result,2))

也许有人可以帮助我,因为我认为有一种特殊的方法来舍入 TimeSpans 而不是正常的小数。

编辑:

我刚刚检查了这样的字符串格式:

$formattedTime = "{0:hh\:mm\:ss}" -f ([TimeSpan] $result)

它看起来不错,但如果日期超过 24 小时,我需要在前面添加天数..所以可能像 'dd'?

Ty 褪色~

您不能将 TimeSpan 对象设置为 DateTime 对象的格式。 为此,您需要将自己的格式字符串放在一起并使用您需要的各个属性:

没有天数:

$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

带天数(相同格式字符串)

$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

TimeSpan 对象的时间属性是 ReadOnly,因此不幸的是您不能将 Milliseconds 设置为 0。

如果您确实想要获得一个 'rounded' TimeSpan 对象,其中毫秒被剥离,您可以这样做:

$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)