【问题标题】:Powershell How to round a TimeSpan?Powershell如何舍入TimeSpan?
【发布时间】:2020-12-03 09:43:25
【问题描述】:

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

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

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

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

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

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

编辑:

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

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

看起来不错,但如果日期超过 24 小时,我需要在前面添加 Days .. 所以可能是 'dd' 之类的?

Ty 褪色了~

【问题讨论】:

    标签: windows powershell shell formatting timespan


    【解决方案1】:

    您不能将 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 对象的时间属性是只读的,因此很遗憾不能将毫秒设置为 0。

    如果您确实想获得一个去掉毫秒的“四舍五入”时间跨度对象,您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 2011-02-09
      • 1970-01-01
      • 2018-07-19
      相关资源
      最近更新 更多