Search code examples
powershelldatetimetimetimezoneutc

Simplest PowerShell method to get current time expressed as UTC


I have reviewed the post Creating a DateTime object with a specific UTC DateTime in PowerShell, but it does not seem to directly answer the question I am asking:

What is the most direct method in PowerShell (3.0) to return a sortable string representing "now" as UTC?

I expected the correct answer to be:

Get-Date -Format (Get-Culture).DateTimeFormat.UniversalSortableDateTimePattern 

OR

Get-Date -Format u

but this is not the case.

Example: At 1300 hrs (1pm) on September 1st, 2016 in the Pacific Time Zone during DST, I get the response:

2016-09-01 13:00:00Z (the local time with a "Z" appended)

when I was expecting:

2016-09-01 20:00:00Z (correct UTC/GMT time)

So basically, my code is just getting a string representing the "local" time and appending a "Z".

Now, I know I can manipulate to get to that point, but I'm looking for the minimal (simplest, cleanest) way to get here.

Bonus Points (as if they existed): How do I get that same, sortable result, but displaying with "UTC" and/or "GMT" as the suffix. Same minimal requirement.


Solution

  • Probably something like this:

    [DateTime]::UtcNow.ToString('u')
    

    Which is equivalent to:

    [DateTime]::UtcNow.ToString((Get-Culture).DateTimeFormat.UniversalSortableDateTimePattern)
    

    For the bonus, I think the most straightforward way is just to replace Z with UTC:

    [DateTime]::UtcNow.ToString('u').Replace('Z','UTC')
    

    I'm assuming you'll always want UTC since that what it seems like from your question. There doesn't appear to be a format string to get just the 3 letter time zone.