Simplest PowerShell method to get current time expressed as UTC
Asked Answered
O

4

17

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.

Osmanli answered 1/9, 2015 at 20:33 Comment(0)
S
31

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.

Saddleback answered 1/9, 2015 at 20:40 Comment(1)
Thanks a bunch, I use this to match the Node new Date().toISOString() format: [DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ss.fffZ')Chrisoula
J
7

If you like to keep using Get-Date for better readability in the code...

(Get-Date).ToUniversalTime()
Johannajohannah answered 26/7, 2023 at 16:42 Comment(0)
M
1

I tried this, and it also gives the result I want:

"[DateTime]::UtcNow.ToString('yyyyMMdd_HHmmss_UTC')"

It is showing time in the format 20180108_152407_UTC so you can play with the date/time formatting as you wish basically

Makepeace answered 8/1, 2019 at 14:26 Comment(0)
C
0

closest to your initial approach would be:

Get-Date -AsUTC -Format "u"

The -format parameter (as the name says) just formats the (local) date into a universal time string - but it doesn't recalculate the date for the given format.

That makes absolute sense, because the format (e.g. 31.12.2017 opposed to 12/31/2017) has nothing to do with time zones at all...

Curtiscurtiss answered 17/7, 2024 at 15:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.