Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 从格式为“的字符串计算总秒数”;HH:mm:ss,fff“;_Powershell_Powershell 2.0_Windows 7 X64 - Fatal编程技术网

Powershell 从格式为“的字符串计算总秒数”;HH:mm:ss,fff“;

Powershell 从格式为“的字符串计算总秒数”;HH:mm:ss,fff“;,powershell,powershell-2.0,windows-7-x64,Powershell,Powershell 2.0,Windows 7 X64,在PowerShell V2中,我想计算给定字符串的总秒数和毫秒数。 我的字符串是00:03:56908,所需的输出是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 有没有更聪明/更短的方法来实现这一

在PowerShell V2中,我想计算给定字符串的总秒数和毫秒数。
我的字符串是
00:03:56908
,所需的输出是
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。但在我的尝试中,这段代码甚至更长了

我不会回避
TotalSeconds
,它在这种情况下很有用。。。合理地说,如果您只是提取该财产:

PS C:\> $a = "00:03:56,908"
PS C:\> $a = [datetime]::ParseExact($a,"HH:mm:ss,fff",$null)
PS C:\> (New-TimeSpan -Start (Get-Date).Date -End $a).TotalSeconds
236.908

newtimespan
放在括号中,允许我们首先计算该语句,然后提取
TotalSeconds
。使用
(Get Date).Date
很重要,因为它定义了午夜,并且由于您将
$a
转换为日期时间,其中日期是今天,我们需要使用今天的午夜作为开始时间。

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

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

哦,我可以控制输入字符串。是不是用一个点而不是逗号来缩短?如
“00:03:56.908”
是,则可以跳过上面的第二行代码。你甚至可以把它写成一行:
[TimeSpan]::Parse(“00:03:56.908”)。TotalSeconds
我太快了。你在评论中的想法给了我
236908
,而不是
236.908
。在字符串旁边。有没有其他方法可以得到点?也许是这样的——DontUseCulture?:)
TimeSpan
对象的
TotalSeconds
属性不是字符串,而是双精度。使用
ToString
方法以您想要的格式打印double应该很简单,并提供您想要的格式。请阅读和上文档页面的更多信息。