Home » PowerShell » PowerShell Epoch Time and DateTime Conversion

PowerShell Epoch Time and DateTime Conversion

The Unix Epoch Time is the number of seconds that have elapsed since January 1, 1970. Using the Get-Date cmdlet with -UFormat %s in PowerShell, it converts the date time to epoch time.

To convert the epoch time to date time, use Microsoft .Net class library System.TimeSpan to add the seconds to the epoch time date of January 01, 1970.

In this article, we will discuss how to convert epoch time to date time and date time to Unix epoch time in PowerShell.

PowerShell Convert DateTime to Epoch Time (Unix Time)

Use the Get-Date cmdlet in PowerShell to specify the date to convert it into epoch time.

# Convert the date time to Unix Epoch Time
Get-Date -Date "20-08-2020" -UFormat %s  

# Convert the current datetime to Unix Timestamp
Get-Date -UFormat %s 

In the above PowerShell script, the Get-Date command uses the Date parameter to specify the custom date and the UFormat %s parameter to convert the specified date to epoch time.

In the next example, the Get-Date cmdlet converts the current DateTime to Unix epoch time using the UFormat %s and returns the total number of seconds elapsed since 01 January 1970.

The output of the above PowerShell script to get epoch time is:

PowerShell DateTime to Epoch Time
PowerShell DateTime to Epoch Time

Cool Tip: How to get-date minus 1 day in PowerShell!

PowerShell Convert Epoch Time To DateTime

Use the Microsoft .Net class library System.TimeSpan in PowerShell to convert Unix timestamp to DateTime.

# Convert Unix Epoch time to DateTime. Add number of seconds to 01-01-1970
$cusDate = (Get-Date -Date "01-01-1970") + ([System.TimeSpan]::FromSeconds((1597881600)))

# Print the datetime
$cusDate

In the above PowerShell script, to convert epoch time to DateTime, add the seconds to the epoch time date 01 January 1970.

The Get-Date command uses the Date parameter to specify the epoch time date and uses concatenation to add the number of seconds to get the date.

The output of the above PowerShell script converts the UNIX epoch time to date time and returns the DateTime.

PS C:\> $cusDate = (Get-Date -Date "01-01-1970") + ([System.TimeSpan]::FromSeconds((1597881600)))

PS C:\> $cusDate              
                                                                                          
20 August 2020 00:00:00

Cool Tip: How to convert string to DateTime in PowerShell!

Conclusion

I hope the above article helped you to understand how to convert DateTime to epoch time in PowerShell and convert Unix timestamp to date time.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.