6

In PowerShell you can format a date to return the current hour like this:

Get-Date -UFormat %H

And you can get a date string in UTC like this:

$dateNow = Get-Date
$dateNow.ToUniversalTime()

But how can you can get the current hour in universal time?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
duncanhall
  • 11,035
  • 5
  • 54
  • 86

1 Answers1

13
Get-Date ([datetime]::UtcNow) -UFormat %H

Up to PowerShell 7.0, Get-Date doesn't directly support formatting the current time based on its UTC value: the formatting options apply to the local representation of the current time.

  • In PowerShell v7.1+ you can use the -AsUTC switch, which enable you to simplify to
    Get-Date -AsUTC -UFormat %H.

However, as shown above, instead of letting Get-Date default to the current (invariably local) time, you can pass a [datetime] instance as an argument to Get-Date('s positionally implied -Date parameter) for reformatting, and [datetime]::UtcNow is the current time expressed in UTC.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    And is there any difference between `(Get-Date).ToUniversalTime()` and `Get-Date ([datetime]::UtcNow)` ? Running both returns the same result for me. Is the `ToUniversalTime()` approach basically doing one more method call compared to the other approach? – iBobb Mar 15 '21 at 13:02
  • 2
    @iBobb, there's no difference in outcome. Yes, `[datetime]::UtcNow` - a single property access on a .NET type - is more efficient than calling a method on the output from a _cmdlet_ (`Get-Date`), but unless you're calling this in a loop with many iterations, it probably won't make a difference in practice. – mklement0 Mar 15 '21 at 13:14