Skip to content

Instantly share code, notes, and snippets.

@rdsimes
Created December 19, 2012 00:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdsimes/4333461 to your computer and use it in GitHub Desktop.
Save rdsimes/4333461 to your computer and use it in GitHub Desktop.
converts a PowerShell/.NET DateTime to a unix timestamp (Milliseconds since 1 Jan, 1970) Useful for creating JSON that can be understood by the .NET JavaScriptSerializer
function ConvertTo-UnixTimestamp {
$epoch = Get-Date -Year 1970 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0
$input | % {
$milliSeconds = [math]::truncate($_.ToUniversalTime().Subtract($epoch).TotalMilliSeconds)
Write-Output $milliSeconds
}
}
Get-Date | ConvertTo-UnixTimestamp
@rdsimes
Copy link
Author

rdsimes commented Dec 19, 2012

Hopefully PS3 will make this redundant

@Siikakala
Copy link

Ancient gist but as I stumbled to this from google, I will leave comment. Even in version 2 there is available Get-Date -UFormat %s, which return unix timestamp with five decimals, so multiplying it will do the trick. Note: it will return System.String, not System.DateTime

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment