13

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.

Community
  • 1
  • 1
dave_the_dev
  • 1,555
  • 3
  • 15
  • 27
  • 3
    `Bonus Points (as if they existed)` [They do exist actually](http://stackoverflow.com/help/bounty) ;-) – briantist Sep 01 '15 at 20:49

3 Answers3

28

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.

briantist
  • 45,546
  • 6
  • 82
  • 127
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

nitinr708
  • 1,393
  • 2
  • 19
  • 29
0

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

(Get-Date).ToUniversalTime()
Dennis
  • 871
  • 9
  • 29