Use UFormat to get unix time

Here's how I do it:

$DateTime = (Get-Date).ToUniversalTime()
$UnixTimeStamp = [System.Math]::Truncate((Get-Date -Date $DateTime -UFormat %s))

Just cast the result to an int like so:

PS> [int][double]::Parse((Get-Date -UFormat %s))
1260172909

PS> "Foo {0:G} Foo" -f [int][double]::Parse((Get-Date -UFormat %s))
Foo 1260172997 Foo

Using the Parse method means the string is parsed "culture aware" such that the appropriate decimal separator character is recognized for the current culture. If you just cast directly, PowerShell uses the invariant culture which causes problems for any culture where decimal sep char is not a period.


[int](Get-Date -UFormat %s -Millisecond 0)

Tags:

Powershell