2012-05-28 61 views
5

我使用PowerShell SQLite模塊解析SQLite數據庫,並且創建和修改了一些返回值,這兩個值都在Unix時間。使用PowerShell轉換Unix時間

我想要做的是以某種方式將其轉換爲「人類時間」。爲了便於閱讀,我刪除了一些其他SQL查詢。

Import-Module SQLite 
mount-sqlite -name GoogleDrive -dataSource E:\Programming\new.db 
$cloud_entry = Get-ChildItem GoogleDrive:\cloud_entry 

foreach ($entry in $cloud_entry) 
{ 
    $entry.created 
} 

我去了以下內容:

$ctime = $entry.created 
[datetime]$origin = '1970-01-01 00:00:00' 
$origin.AddSeconds($ctime) 

輸出類似於Unix的時間戳的大柱:

1337329458 

回答

12

http://codeclimber.net.nz/archive/2007/07/10/convert-a-unix-timestamp-to-a-.net-datetime.aspx

您可以輕鬆地在PowerShell中重現此。

$origin = New-Object -Type DateTime -ArgumentList 1970, 1, 1, 0, 0, 0, 0 
$whatIWant = $origin.AddSeconds($unixTime) 

編輯:對不起,更正了錯誤。

+5

'[DATETIME] $起源=「1970-01-01 00:00:00''作品一樣好,和也許有點容易理解 –

+0

我得到這個錯誤:任何想法?無法將參數「0」轉換爲「AddSeconds」的值:「」。其中一些值爲「空」,因爲數據庫中的某些項目未被指定爲創建/修改日期。我假設這是錯誤來自哪裏。 – mrwh1t3

1
$ctime = $entry.created 
[datetime]$origin = '1970-01-01 00:00:00' 
$origin.AddSeconds($ctime) 
8
Function Convert-FromUnixDate ($UnixDate) { 
    [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($UnixDate)) 
} 

$niceTime = Convert-FromUnixDate $ctime 

PS C:\> $niceTime 

Friday, 18 May 2012 8:24:18 p.m. 
2
$date = get-date "1/1/1970" 
$date.AddSeconds($unixTime).ToLocalTime() 
1

一個簡單的襯墊:

(Get-Date "1970-01-01 00:00:00.000Z") + ([TimeSpan]::FromSeconds($unixTime))