#PSTip How to check if a DateTime string is in a specific pattern

You want to be able to check and allow only date and time strings that are in a specific date time format pattern. For example, you get a string and want to check if it is in a sortable date and time pattern.

Let’s find first how a sortable date and time string looks like. Note that format string is culture dependent:

PS> (Get-Culture).DateTimeFormat.SortableDateTimePattern
yyyy'-'MM'-'dd'T'HH':'mm':'ss

Instead of using, or having to remember that long pattern, the .NET Framework offers us a composite format string

that is an equivalent of the above, kind of a shortcut pattern, the “s” standard format string. We can format a date and time object to a sortable pattern with the Get-Date cmdlet.

PS> Get-Date -Format s
2013-07-05T11:45:10

Now, given a date and time string, how you check it complies to a specific pattern?

The DateTime .NET structure has a static method we can use to parse strings and return DateTime objects, the ParseExact method. It converts the specified string representation of a date and time to its DateTime equivalent. If the format of the string does not match a specified format exactly an exception is thrown.

The method accepts three arguments:

  1.  s – A string that contains a date and time to convert.
  2. format – A format specifier that defines the required format of ‘s’.
  3. provider – An object that supplies culture-specific format information about ‘s’.

Wrapping it all into a function so we can reuse it any time we need to.

function Test-DateTimePattern
{
    param(
        [string]$String,
        [string]$Pattern,
        [System.Globalization.CultureInfo]$Culture = (Get-Culture),
        [switch]$PassThru
    )
    $result = try{ [DateTime]::ParseExact($String,$Pattern,$Culture) } catch{}

    if($PassThru -and $result)
    {
        $result
    }
    else
    {
        [bool]$result
    }
}

The function returns True/False if a given string is in the correct format. Add the PassThru switch to get back the parsed date and time object if the pattern was successfully parsed.

PS> Test-DateTimePattern -String '12:15 PM' -Pattern t
True

# invalid pattern, missing the AM/PM designator (try Get-Date -f g)
PS> Test-DateTimePattern -String '7/5/2013 12:16' -Pattern g
False

PS> Test-DateTimePattern -String '2013-07-05T11:45:12' -Pattern s -PassThru
Friday, July 5, 2013 11:45:12 AM

# invalid pattern, pattern should be in dd/MM/yyyy
PS> Test-DateTimePattern -String '12/14/2013' -Pattern d -Culture he-IL
False
Share on: