#PSTip Converting a String to a System.DateTime object
In a perfect world all date and time data available are represented by System.DateTime objects. In the real world we are usually not that lucky. You get lot of obscurely formatted dates that you have to convert yourself. The .NET Framework offers a special method just for that, TryParseExact(). Calling the method is not particularly easy so I’ve created a short function to make it easier to work with:
function Convert-DateString ([String]$Date, [String[]]$Format)
{
$result = New-Object DateTime
$convertible = [DateTime]::TryParseExact(
$Date,
$Format,
[System.Globalization.CultureInfo]::InvariantCulture,
[System.Globalization.DateTimeStyles]::None,
[ref]$result)
if ($convertible) { $result }
}
Let’s call it with a date string in an uncommon format and see how the function handles different date and time separators:
Convert-DateString -Date '12/10\2013 13:26-34' -Format 'dd/MM\\yyyy HH:mm-ss' Saturday, October 12, 2013 1:26:34 PM
The function successfully converts the date and returns a DateTime object. If the operation was not successful nothing would have been returned.
Also notice the Format parameter accepts array of strings, allowing you to specify more than one format of the input.
Convert-DateString -Date '12:26:34' -Format 'HH:mm:ss','HH-mm-ss'
Convert-DateString -Date '12-26-34' -Format 'HH:mm:ss','HH-mm-ss'
Thursday, July 4, 2013 12:26:34 PM
Thursday, July 4, 2013 12:26:34 PM
The string is converted successfully, and because only time was provided, today’s date is used to complete the other date parts of the object.
Building a format string
Providing correct string to the Format parameter is essential for successfully using the function. Let’s have a quick look on how to create one yourself: The string uses the following characters “d”, “f”, “F”, “g”, “h”, “H”, “K”, “m”, “M”, “s”, “t”, “y”, “z” to define type, position and format of the input values. The type of the input value (day, month, minute etc.) is defined by choosing the correct letter to represent the value (day d, month M, minute m etc.), case matters here. The position is defined by placing the character on the correct place in the string. The format is defined by how many times the character is repeated (d to represent 1-31, dd for 01-31, dddd for Monday).
Convert-DateString -Date 'Thursday, July 4, 2013 12:26:34 PM' `
-Format 'dddd, MMMM d, yyyy hh:mm:ss tt'
Thursday, July 4, 2013 12:26:34 PM
If your string contains any of the listed characters or the backslash (“\”) character you have to escape it by preceding it with a backslash:
Convert-DateString -Date "d: 01\01\2013" -Format '\d: dd\\MM\\yyyy'
Tuesday, January 1, 2013 12:00:00 AM
The complete reference to creating custom date and time format strings, as well as many examples may be found here.
Share on: