PowerShell: How to Convert Unix Timestamp to Datetime


Often you may want to convert a Unix timestamp to a readable datetime in PowerShell.

You can use the following syntax to do so:

(([System.DateTimeOffset]::FromUnixTimeSeconds($my_unix_time)).DateTime.ToLocalTime()).ToString("s")

This particular example will convert the Unix timestamp stored in the variable named $my_unix_time to a readable datetime.

Note that PowerShell will display the output in UTC in a 24-hour format. By using ToLocalTime() we are able to cover the resulting datetime to the local time on our machine.

Also note you could also use the function FromUnixTimeMilliseconds to convert a Unix time stored in milliseconds to a readable datetime.

The following example shows how to use this syntax in practice.

Example: How to Convert Unix Timestamp to Datetime in PowerShell

Suppose that we would like to convert the Unix timestamp 1667614523 into a readable datetime.

We can use the following syntax to do so:

$my_unix_time=1667614523
(([System.DateTimeOffset]::FromUnixTimeSeconds($my_unix_time)).DateTime.ToLocalTime()).ToString("s") 

The following screenshot shows how to use this syntax in practice:

PowerShell convert unix timestamp to datetime

Notice that this returns the following datetime:

  • 2022-11-04T22:15:23

Note that you can specify whatever format you would like to use within the ToString() method to instead display the resulting datetime in a different format.

For example, we could use the following syntax to return the datetime formatted as MM/dd/yyyy instead:

$my_unix_time=1667614523
(([System.DateTimeOffset]::FromUnixTimeSeconds($my_unix_time)).DateTime.ToLocalTime()).ToString("MM/dd/yyyy") 

The following screenshot shows how to use this syntax in practice:

PowerShell convert unix timestamp to date with specific format

Notice that this returns the following date:

  • 11/04/2022

Feel free to use whatever datetime format you would like within the ToString() method.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Compare Dates
PowerShell: How to List Files in Directory by Date
PowerShell: Get List of Files Modified After Certain Date
PowerShell: Check if File Has Been Modified in last 24 Hours

Leave a Reply