Created
July 11, 2025 16:56
-
-
Save griffeth-barker/fea781e93fb5d6f73b7821b207c8747a to your computer and use it in GitHub Desktop.
Converting between Unix timestamps and DateTime objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ConvertFrom-UnixTimestamp { | |
<# | |
.SYNOPSIS | |
Converts a Unix timestamp to a DateTime object. | |
.DESCRIPTION | |
Converts a Unix timestamp to a DateTime object. | |
.PARAMETER Milliseconds | |
The Unix timestamp to convert. | |
.INPUTS | |
String | |
.OUTPUTS | |
DateTime | |
.EXAMPLE | |
ConvertFrom-UnixTimestamp -Milliseconds 1747927975516 | |
# Converts the Unix timestamp to a DateTime object. | |
# Example output: | |
# Thursday, May 22, 2025 8:32:55 AM | |
#> | |
param( | |
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
[string]$Milliseconds | |
) | |
begin {} | |
process { | |
$output = ( [DateTime]::UnixEpoch ).AddMilliseconds( $Milliseconds ).ToLocalTime() | |
Write-Output $output | |
} | |
end {} | |
} | |
function ConvertTo-UnixTimestamp { | |
<# | |
.SYNOPSIS | |
Converts a DateTime object to a Unix timestamp. | |
.DESCRIPTION | |
Converts a DateTime object to a Unix timestamp. | |
.PARAMETER DateTime | |
The DateTime object to convert. | |
.INPUTS | |
DateTime | |
.OUTPUTS | |
String | |
.EXAMPLE | |
ConvertTo-UnixTimestamp -DateTime (Get-Date) | |
# Converts the DateTime object for today's date to a Unix timestamp. | |
# Example output: | |
# 1752252878823 | |
#> | |
param( | |
[Parameter(Mandatory = $true, ValueFromPipeline = $true)] | |
[DateTime]$DateTime | |
) | |
begin {} | |
process { | |
$output = [math]::Round( ($DateTime.ToUniversalTime() - [DateTime]::UnixEpoch).TotalMilliseconds ) | |
Write-Output $output | |
} | |
end {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment