39

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?

3

4 Answers 4

61

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
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. Jan 28, 2020 at 11:29
36

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'
6
  • 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, 2019 at 19:33
  • 1
    "%F" works with PowerShell 7: get-date -UFormat "%F" produces the expected format.
    – jgran
    Aug 6, 2020 at 8:15
  • 3
    This will give you a timestamp in the local timezone! The "Z" suffix may be incorrect.
    – cidermole
    Nov 2, 2020 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. Jul 8, 2021 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) Jul 8, 2021 at 13:57
12

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"

11

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")
1
  • 1
    Worth noting that this works all the way back to PowerShell v1. Sep 6, 2022 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.