Windows ISO 8601 timestamp
Asked Answered
C

4

43

I need to convert a date in Windows PowerShell to the ISO 8601 format.

In Linux/Unix it was no problem with

TZ=0 date -d "<random-format>" +%Y-%m-%dT%H:%M:%S.000Z

Now I need to do the same in Windows PowerShell. The output format on Windows is

Wednesday, 19. July 2017 01:06:13

How can I do it?

Corr answered 15/8, 2017 at 8:45 Comment(3)
See: techontip.wordpress.com/2016/10/10/….Pallette
Get-Date -Format oDiatomaceous
Anyone know why this is not documented here? Custom date and time format stringsFayfayal
D
64

PowerShell's Get-Date supports standard .NET time formats. The o round-trip format complies with ISO 8601. Like so,

Get-Date -Format "o"

2017-08-15T12:10:34.4443084+03:00
Demoralize answered 15/8, 2017 at 9:13 Comment(1)
Despite of the possible portability problem, I like this solution because it is simple and you can basically memorize it for your quickly-written scripts.Disabled
D
37

Get-Date supports Unix formatting strings with the -UFormat parameter. You can reuse it:

Get-Date (Get-Date).ToUniversalTime() -UFormat '+%Y-%m-%dT%H:%M:%S.000Z'
Diatomaceous answered 15/8, 2017 at 10:34 Comment(6)
This should be the correct answer, since the question was framed in a way that suggests portability is important. However the implementation in Powershell is incomplete, so formatting elements like %F do not work, although %T does; nor is there any apparent way to simply specify UTC time like Unix date has these days.Provided
"%F" works with PowerShell 7: get-date -UFormat "%F" produces the expected format.Antependium
This will give you a timestamp in the local timezone! The "Z" suffix may be incorrect.Outbound
It is incorrect, as I just both did Get-Date -Format "o" and Get-Date -UFormat '+%Y-%m-%dT%H:%M:%S.000Z' and got the same time, while I live at UTC+3.Dowson
@MelvinRoest In Windows PowerShell or a newer version? I just tried in WPS 5.1 on a machine with UTC+2 and it spits out local time, not universal (answer has been updated)Diatomaceous
I used PowerShell 5.1Dowson
G
13

The following works both in Windows PowerShell 5.1 and PowerShell 7.0 on Windows/OS X:

 (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffK")
 
 2020-12-01T22:31:41.402Z

If you don't want your milliseconds, then format string would be "yyyy-MM-ddTHH:mm:ss.000K"

Gagger answered 1/12, 2020 at 23:13 Comment(0)
T
12

Old question but since none of the other answers has it, if you're looking for UTC, this seems to do it:

(Get-Date).ToUniversalTime().ToString("o")
Trueblood answered 4/5, 2022 at 10:39 Comment(1)
Worth noting that this works all the way back to PowerShell v1.Termitarium

© 2022 - 2024 — McMap. All rights reserved.