2008-08-14

ISO 8601 date formatting using PowerShell

My favorite timestamp is the ISO 8601 format [YYYY]-[MM]-[DD]T[hh]:[mm]:[ss.sss]Z.
The ISO 8601 standard is very well described in a Wikipedia article (ISO 8601).

I do miss a ISO formatting option in .NET/PowerShell, but using DateTime formatting, an acceptable result is found:
$theDate = Get-Date
"{0:yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffff'Z'}" -f $theDate.ToUniversalTime()
$theDate.ToUniversalTime().ToString( "yyyy-MM-ddTHH:mm:ss.fffffffZ" )
The formatting is shown twice using different syntax.
I've chosen seven digits on the second because I have logging in mind while working with time stamp. I have (once) seen that three digits wasn't enough - it was in a technical database log on a z/Server "mainframe".

A execution gives this result:
2008-01-13T10:02:36.8992896Z
I would like to get the week of the year, but again this is a problem. Is it because a week number is more used in Europe than on the other side of the Atlantic?
Thomas Lee has tried (eggheadcafe conversation), and I tried his examples. I regret to say he's right – again.

Using the formatting specifier 'o' (oscar) from the DateTimeFormatInfo Class to the CmdLet Get-Date will generate a output with seven digits, but also a a part with a reference to the timezone. Mark Puckett has made a comment to this post about this possibility. And he is right that this specifier wil give a output that is very precise. But I choose not to use this as I go for UTC time in a log as I think it makes the log entries more readable on senior management level.

History

2008-01-14 Blog post created
2017-02-05 Section on -Format o added inspired by comment by Mark Puckett.

3 comments:

Arley Dealey said...

I think .Net/PowerShell can give you everything you want natively. See this article:

http://technet.microsoft.com/en-us/library/ee692801.aspx

The only caution I would add is that the -z format will FORMAT the output as Zulu time but the VALUE of the output is still local time, not Zulu!

Niels Grove-Rasmussen said...

@Arley: It is correct that the .NET formatting can be done by ISO 8601 with -s, but I wanted more decimals. I am sorry that I did not write that requirement in the blog entry.

Mark Puckett said...

guys, try -format o