在PowerShell中将秒转换为hh:mm:ss,fff格式

时间:2014-02-18 00:41:31

标签: powershell powershell-v2.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

实现这一目标的正确方法是什么?我确信-f和日期时间更加优雅。

3 个答案:

答案 0 :(得分:22)

在PowerShell 4.0中

$s = "7000.6789"
$ts =  [timespan]::fromseconds($s)
("{0:HH\:mm\:ss\,fff}" -f $ts)

输出:01:56:40,679


在PowerShell 2.0中

$s = "7000.6789"
$ts =  [timespan]::fromseconds($s)
"{0:HH:mm:ss,fff}" -f ([datetime]$ts.Ticks)

输出:01:56:40,679


然后以另一种方式回去......

$text = "01:56:40,679"
$textReformat = $text -replace ",","."
$seconds = ([TimeSpan]::Parse($textReformat)).TotalSeconds
$seconds

输出:7000.679

答案 1 :(得分:9)

您可以在TimeSpan对象上使用ToString方法并指定要使用的格式。使用其中一个standard timespan formats或使用custom timespan format。例如,以下自定义格式提供了所需的输出:

$ts =  [timespan]::fromseconds("7000.6789")
$ts.ToString("hh\:mm\:ss\,fff")

这将输出

01:56:40,679

更新:更新以提供在PowerShell v2中运行的功能

上述解决方案在PowerShell v4中运行良好,但在v2中运行不正确(因为在.NET Framework 4之前未添加TimeSpan.ToString(string)方法)。

在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)
}

使用

进行测试
$ts =  [timespan]::fromseconds("7000.6789")

Format-TimeSpan -TimeSpan $ts
$ts | Format-TimeSpan

产生以下输出:

01:56:40,679
01:56:40,679

答案 2 :(得分:1)

一行转换:

[timespan]::fromseconds(354801857.86437).tostring()

返回4106.12:04:17.8640000