Converting from UNIX time to a PoSh DateTime object

2 04 2010

Suppose you have a log file from a UNIX/Linux (or some derivative) system which has timestamps in UNIX time format and you want to convert them to shiny DateTime objects. Here’s an example of how to do that, wrapped in a PowerShell function for convenience:

Function get-Unixdate ($UnixDate) {
    [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').`
    AddSeconds($UnixDate))
}

It returns a PowerShell DateTime object, so can then be manipulated using the standard DateTime methods, eg

PS> $logtime = Get-UnixDate 1269313872.893866062
PS> $logtime

Tuesday, 23 March 2010 4:11:12 p.m.

PS> $logtime.IsDaylightSavingTime()
True
PS> $logtime.dayofweek
Tuesday
PS> $logtime.minute
11
PS> $logtime.tostring("g")
23/03/2010 4:11 p.m.
PS> $logtime.DayOfYear
82
PS> $logtime.AddDays(-30)

Sunday, 21 February 2010 4:11:12 p.m.

PS> ($logtime.adddays(14)).isdaylightsavingtime()
False

etc.

I have added the function to my profile, it comes in useful quite often.

Here’s some tips on working with PowerShell DateTime objects and the MSDN documentation on formatting DateTime output

Advertisement

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.