Search code examples
powershelldatetimeunix-timestamp

What is the most "idiomatic" way to get Unix seconds from PowerShell?


I'm used to using the .NET Framework DateTimeOffset to get Unix seconds.

PS> ([datetimeoffset] '2020-01-01').ToUnixTimeSeconds()
1577854800

But, I'm writing a PowerShell script and thought I'd try to be as "idiomatic" as possible. It seemed like Get-Date would do the trick, but the results are different.

PS> Get-Date -Date '2020-01-01' -UFormat %s
1577836800

It seems like Get-Date is synonymous with DateTime, using my local timezone, by default. The only way I can get a UTC date from Get-Date is another .NET method call.

PS> (Get-Date -Date '2020-01-01').ToUniversalTime()

And, now, to get Unix seconds, I can pipe again?

PS> (Get-Date -Date '2020-01-01').ToUniversalTime() | Get-Date -UFormat %s

That's an awful lot of piping for what I thought would be a simple expression... any other ideas?


Solution

  • OK, so, until Get-Date becomes timezone aware or we get a new cmdlet... it seems we have to use the ToUniversalTime method. It's especially important to consider because this bug seems to only effect formatting Unix seconds if you haven't converted to Universal time (a fix is merged, but who knows what release that's in).

    So, the best we can do is probably something like this:

    PS> Get-Date -Date (Get-Date -Date '2020-01-01').ToUniversalTime() -UFormat %s