Calculating Time Differences Using Custom Formats

by Mar 11, 2013

Calculating time differences is easy – provided you can convert the date and time information into a DateTime type. If the date is in a custom format, you can use the method ParseExact() and submit your own pattern.

So if you have custom dates formatted as “MonthnameDay” (for example, ‘January16’), here is how you turn this into a true DateTime and calculate the time difference:

$text = 'January16'
[System.Globalization.CultureInfo]$US = 'en-US'
$date = [System.DateTime]::ParseExact($text, 'MMMMdd', $US)

Likewise, if the custom format uses localized month names (for example German names such as ‘Januar16’), adjust the culture information:

$text = 'Januar16'
[System.Globalization.CultureInfo]$US = 'de-DE'
$date = [System.DateTime]::ParseExact($text, 'MMMMdd', $US)

Twitter This Tip! ReTweet this Tip!