2014-02-18 144 views
8

我有一個字符串表示時間(以秒和毫秒爲單位)。我想將它轉換爲格式爲「hh:mm:ss,fff」的字符串。在PowerShell中將秒轉換爲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和日期時間有一個更優雅的方式。

+0

'$ res.ToString()'是否滿足您的要求?如果沒有相關數字,它會跳過毫秒,如果小時數高於23,它會附加日期,這可能不適合您。如果這不起作用,請查看採用格式字符串的'TimeSpan.ToString(string)'方法。格式字符串可以是[標準時間段格式](http://msdn.microsoft.com/zh-cn/library/ee372286(v = vs.110).aspx)或[自定義時間段格式](http: //msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx)。 –

回答

20

在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

+0

謝謝andyb,這工作得很好! (我很自由,插入完整的例子,隨時回滾)。一個例子將如何查找這個的完全相反?例如從'01:56:40,697'到'7000.6789' – nixda

+0

是 - 請參閱編輯:) – andyb

+0

PowerShell V2解決方案適用於我的一些場景,但對於> = 13小時的持續時間,hh字段將返回01-12 。 –

6

你可以只使用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()並操縱字符串。我建議前者。下面是其爲正常工作的功能:使用

$ts = [timespan]::fromseconds("7000.6789") 

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

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

測試產生以下的輸出:

01:56:40,679 
01:56:40,679 
+0

謝謝羅伯特,我不知道'TimeSpan.ToString(string)'是後來添加的。 – nixda

0

一號線轉換:

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

回報4106.12:04:17.8640000

相關問題