#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

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

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
        [System.Globalization.CultureInfo]$Culture = (Get-Culture),

    $result = try{ [DateTime]::ParseExact($String,$Pattern,$Culture) } catch{}

    if($PassThru -and $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

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

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

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: