Posted in : Microsoft By Vikingur Saemundsson Translate with Google ⟶

2 years ago

A collegue of mine asked if there is a way to output a RFC compliant datetime (https://www.ietf.org/rfc/rfc3339.txt) in powershell without manually formatting in T and Z in the middle and end to comply with ISO standard and imply UTC +-00:00
 

Before i start with the how, I’d like to address the why.

If you’ve ever done some coding you’re sure to have encountered issues with datettime and possibly errors and incidents due to the timeformat of a datetime string.
For example, if I live in the US then time is commonly written in month-day-year format, which during the first 12 days of each month is indistinguishable from the european day-month-year format.
This is also encountered in code, for example in powershell my locale is Swedish and the ”Get-Date” cmdlet returns ”den 1 augusti 2018 16:35:24” which is easy and readable for a human.
However if i convert it to a string it becomes in US format even though my culture settings in powershell is set to swedish.
In my opinion this behavior is wrong as I expect to be given a ISO standard universal format, or at least a culture appropriate format. Instead I am given a US format.

PS C:\> "$(Get-Date)"
08/01/2018 16:35:27
PS C:\> Get-Culture
LCID Name DisplayName
---- ---- -----------
1053 sv-SE Swedish (Sweden)

With that said, developing automation and tools for global customers a standard format is much needed when we write to logs.

The How

After a short time on google it seems no one had done this properly in powershell. I also found out that XML is RFC compliant.
How did i do it?

[Xml.XmlConvert]::ToString((get-date),[Xml.XmlDateTimeSerializationMode]::Utc)

Returns:

2018-08-01T14:23:46.851301Z

Great! Now let’s put it into some real code.
Example 1: Writing current date into a logfile

$Now = [Xml.XmlConvert]::ToString((get-date),[Xml.XmlDateTimeSerializationMode]::Utc)
"$Now || Restarting server" | Out-File $logfile -Append

The output becomes a RFC compliant string and gets stored in the $now variable to be used into a out-file log operation.
Example 2: Writing a job deadline datettime

$Deadline = (Get-date).AddHours(20)
$RFCDeadline = [Xml.XmlConvert]::ToString($Deadline,[Xml.XmlDateTimeSerializationMode]::Utc)
$Now = [Xml.XmlConvert]::ToString((get-date),[Xml.XmlDateTimeSerializationMode]::Utc)
"$Now || Server will be restarted at $RFCDeadline" | Out-File $logfile -Append

Here we create a datettime object, add 20 hours and then convert it to a RFC compliant datettime string and store it into the $RFCDeadline variable.
Hope this helps someone!

Tags : datetime, PowerShell, XML

Personlig rådgivning

Vi erbjuder personlig rådgivning med författaren för 1400 SEK per timme. Anmäl ditt intresse i här så återkommer vi så snart vi kan.

Add comment

Your comment will be revised by the site if needed.