gpt4 book ai didi

powershell - 从格式为 "HH:mm:ss,fff"的字符串计算总秒数

转载 作者:行者123 更新时间:2023-12-04 02:17:19 24 4
gpt4 key购买 nike

在 PowerShell V2 中,我想计算给定字符串的总秒数和毫秒数。
我的字符串是 00:03:56,908,所需的输出是 236.908

我的工作,但笨拙的代码是

$a = "00:03:56,908"
$a = [datetime]::ParseExact($a,"HH:mm:ss,fff",$null)
[string]($a.Hour*3600 + $a.Minute*60 + $a.Second) +"."+ [string]$a.Millisecond

是否有更智能/更短的方法来实现这一点?


我发现的只是来自 TimeSpan 对象的 .totalseconds。但是这段代码在我的尝试中甚至更长

最佳答案

TimeSpan 类在早于 4.0 的 .NET 版本中的问题是它不能很好地处理不同的区域性或格式化字符串。鉴于您的字符串有一个逗号而不是一个句点,如果我们想将它解析为一个时间跨度,我们将不得不更改它,但我认为这仍然是最好的方法。

$timeString = "00:03:56,908"
$timeStringWithPeriod = $timeString.Replace(",",".")
$timespan = [TimeSpan]::Parse($timestringWithPeriod)
$totalSeconds = $timespan.TotalSeconds

关于powershell - 从格式为 "HH:mm:ss,fff"的字符串计算总秒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com