Converting UNIX Time to DateTime

by Oct 14, 2021

“Unix time” counts the seconds that have passed since 01/01/1970.

For example, in Windows, you can read the installation date from the Windows Registry, and the returned value is “Unix time”:

$values = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' 
$installDateUnix = $values.InstallDate

$installDateUnix

The result is a large number similar to this:

 
1601308412 
 

To convert “Unix time” to a real DateTime value, .NET Framework provides a type called [DateTimeOffset]:

$values = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' 
$installDateUnix = $values.InstallDate

[DateTimeOffset]::FromUnixTimeSeconds($installDateUnix)

Now you get back different date and time representations:

 
DateTime      : 28.09.2020 15:53:32
UtcDateTime   : 28.09.2020 15:53:32
LocalDateTime : 28.09.2020 17:53:32
Date          : 28.09.2020 00:00:00
Day           : 28
DayOfWeek     : Monday
DayOfYear     : 272
Hour          : 15
Millisecond   : 0
Minute        : 53
Month         : 9
Offset        : 00:00:00
Second        : 32
Ticks         : 637369052120000000
UtcTicks      : 637369052120000000
TimeOfDay     : 15:53:32
Year          : 2020 
 

To get the installation time in local time, you could melt it all together in a one-liner:

 
PS> [DateTimeOffset]::FromUnixTimeSeconds((Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').InstallDate).DateTime

Moday, September 28, 2020 15:53:32
 


Twitter This Tip! ReTweet this Tip!