2013-03-07 70 views
0

我正在尋找一種將軍用時間字符串(「22:12:02」)轉換爲日期時間對象的方法。Powershell - 將軍事時間字符串轉換爲datetime

下面的代碼示例:

$TimePrevious = $Null 
[array]$TimeArray = "22:12:02.000", "22:12:03.000", "23:12:02.000" 

$TimeArray | ForEach-Object { 
    $TimeCurrent = $_.Substring(0,8) 
    $TimeDifference = [datetime]$TimeCurrent.TimeOfDay - [datetime]$TimePrevious.TimeOfDay 
    If ($TimeDifference.Second -lt "10") {Write-Host "$_ is less than 10 seconds"} 
    $TimePrevious = $_ 
    } 

錯誤顯示爲「無法轉換‘System.TimeSpan 22時12分02秒’型的價值‘’輸入‘的System.DateTime’

+2

我想知道你爲什麼稱之爲「軍事」?這是一個常規時間格式。 – 2013-03-07 23:15:26

+0

@a_horse_with_no_name:**確切地說!! ** **整個世界**(美國除外)基本上使用24小時時間格式......它應該被稱爲**標準時間格式**或其他。 .. – 2013-03-08 06:11:29

回答

3

默認解析器似乎與合作:

[datetime]"22:12:02" 

週四,2013年3月7日下午10時12分02秒

0

對不起。我剛剛得到這個工作:

$TimePrevious = $Null 
[array]$TimeArray = "22:12:02.000", "22:12:03.000", "23:12:02.000" 

$TimeArray | ForEach-Object { 
    $TimeCurrent = $_.Substring(0,8) 
    $TimeDifference = [datetime]$TimeCurrent - [datetime]$TimePrevious 
    If ($TimeDifference.TotalSeconds -lt "10") {Write-Host "$_ is less than 10 seconds"} 
    $TimePrevious = $_ 
    } 

感謝您的快速答覆。