nix*_*xda 11 powershell powershell-2.0 windows-7-x64
我有一个字符串表示以秒和毫秒为单位的时间.我想将其转换为格式为"hh:mm:ss,fff"的字符串.
我的解决方案仍有缺陷,小于10的小时显示为一个小数而不是两个:
PS> $secs = "7000.6789"
PS> $ts = [timespan]::fromseconds($s)
PS> $res = "$($ts.hours):$($ts.minutes):$($ts.seconds),$($ts.milliseconds)"
PS> $res
PS> 1:56:40,679
Run Code Online (Sandbox Code Playgroud)
实现这一目标的正确方法是什么?我确信有更优雅的方式-f
和日期时间.
and*_*dyb 25
在PowerShell 4.0中
$s = "7000.6789"
$ts = [timespan]::fromseconds($s)
("{0:hh\:mm\:ss\,fff}" -f $ts)
Run Code Online (Sandbox Code Playgroud)
输出: 01:56:40,679
在PowerShell 2.0中
$s = "7000.6789"
$ts = [timespan]::fromseconds($s)
"{0:hh:mm:ss,fff}" -f ([datetime]$ts.Ticks)
Run Code Online (Sandbox Code Playgroud)
输出: 01:56:40,679
然后回到另一个方向......
$text = "01:56:40,679"
$textReformat = $text -replace ",","."
$seconds = ([TimeSpan]::Parse($textReformat)).TotalSeconds
$seconds
Run Code Online (Sandbox Code Playgroud)
输出: 7000.679
Rob*_*und 10
您可以ToString
在TimeSpan对象上使用该方法并指定要使用的格式.使用标准时间跨度格式之一或使用自定义时间跨度格式.例如,以下自定义格式提供您想要的输出:
$ts = [timespan]::fromseconds("7000.6789")
$ts.ToString("hh\:mm\:ss\,fff")
Run Code Online (Sandbox Code Playgroud)
这将输出
01:56:40,679
Run Code Online (Sandbox Code Playgroud)
更新:更新以提供在PowerShell v2中工作的功能
上面的解决方案在PowerShell v4中运行良好,但在v2中运行不正确(因为TimeSpan.ToString(string)
直到.NET Framework 4才添加该方法).
在v2中我想你必须手动创建字符串(就像你在问题中做的那样)或者做一个普通的ToString()
操作字符串.我建议前者.这是一个适用于此的功能:
function Format-TimeSpan
{
PARAM (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[TimeSpan]$TimeSpan
)
#Current implementation doesn't handle days.
#By including the delimiters in the formatting string it's easier when we contatenate in the end
$hours = $TimeSpan.Hours.ToString("00")
$minutes = $TimeSpan.Minutes.ToString("\:00")
$seconds = $TimeSpan.Seconds.ToString("\:00")
$milliseconds = $TimeSpan.Milliseconds.ToString("\,000")
Write-Output ($hours + $minutes + $seconds + $milliseconds)
}
Run Code Online (Sandbox Code Playgroud)
使用它进行测试
$ts = [timespan]::fromseconds("7000.6789")
Format-TimeSpan -TimeSpan $ts
$ts | Format-TimeSpan
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
01:56:40,679
01:56:40,679
Run Code Online (Sandbox Code Playgroud)
一行转换:
[timespan]::fromseconds(354801857.86437).tostring()
Run Code Online (Sandbox Code Playgroud)
返回4106.12:04:17.8640000
归档时间: |
|
查看次数: |
35591 次 |
最近记录: |