Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get formatted universal date / time

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?

like image 508
duncanhall Avatar asked Dec 24 '22 00:12

duncanhall


1 Answers

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.

like image 147
mklement0 Avatar answered Jan 18 '23 21:01

mklement0