Wednesday, December 30, 2020

PowerShell: Working with UTC Date/Time Values, String Representations and Parsing

The previous post on PowerShell enumerations (see PowerShell: Enumerations) actually demonstrated PowerShell's support for UTC date/time, how to format UTC dates as text, and how to covert a string to UTC time. The sample code in the aforementioned post created a log entry class that uses UTC time versus local time (see line 25):

In the code above the Get-Date cmdlet retrieves the current/date time and the DateTime structure's ToUniversalTime method converts the local time to UTC.

When a log entry (class SimpleLogEntry) instance is written as a line of text so it can be logged, the code to perform this task is as follows (the ToString method of the SimpleLogEntry class):


The GetDateTmeText method above converts the date/time associated with log entry to text using:

$this.dateTime.ToString('o')

The 'o' is one of .NET standard date/time formatters (see Standard date and time format strings). As the documentation from Microsoft below states, the 'o' format produces a string but can be parsed back to the original date:


The code that parses the date/time in string format in order to construct a new instance of SimpleLogEntry is as follows:


The code at line 41 first casts the string to a DateTime structure which creates a date/time object corresponding to local time:

[DateTime]$items[[LogItemIndex]::Date]

Invoking the ToUniversalTime method converts the local time to UTC:

([DateTime]$items[[LogItemIndex]::Date]).ToUniversalTime()

With that the round trip is complete from UTC date/time to string and back to UTC date/time.





No comments :

Post a Comment