Functions/ConvertTo-DateTime.ps1
|
<#
.SYNOPSIS Converts a string representation of a date and time to a DateTime object. .DESCRIPTION The ConvertTo-DateTime function takes a string representation of a date and time and attempts to convert it to a DateTime object. The function supports multiple date and time formats and returns an error if the input string cannot be parsed. .PARAMETER DateString The string representation of the date and time to convert. .EXAMPLE ConvertTo-DateTime -DateString "2022-12-31T23:59:59.999Z" Returns a DateTime object representing December 31, 2022 at 11:59:59.999 PM UTC. #> function ConvertTo-DateTime { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string]$DateString ) $formats = [System.String[]]@( "yyyy-MM-ddTHH:mm:ss.fffZ", "yyyy-MM-ddTHH:mm:ss.ffZ", "yyyy-MM-ddTHH:mm:ss.fZ" ) $date = new-object System.DateTime try { [DateTime]::TryParseExact($DateString, $formats, [System.IFormatProvider]::("2022-12-31T23:59:59"), [System.Globalization.DateTimeStyles]::None, [ref]$date) } catch { continue } if ($date) { return $date } else { throw "Error parsing date" } } |