38

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M.S.
  • 485
  • 1
  • 4
  • 7

4 Answers4

57

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vonPryz
  • 22,996
  • 7
  • 54
  • 65
34

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'
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 1
    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. – Rich Apr 11 '19 at 19:33
  • 1
    "%F" works with PowerShell 7: `get-date -UFormat "%F"` produces the expected format. – jgran Aug 06 '20 at 08:15
  • 3
    This will give you a timestamp in the local timezone! The "Z" suffix may be incorrect. – cidermole Nov 02 '20 at 16:09
  • 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. – Melvin Roest Jul 08 '21 at 13:24
  • @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) – Mathias R. Jessen Jul 08 '21 at 13:57
  • I used PowerShell 5.1 – Melvin Roest Jul 08 '21 at 16:50
11

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"

sokhaty
  • 418
  • 3
  • 8
9

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")
rom99
  • 709
  • 4
  • 14