How-to: Use ParseExact to convert a Date String to DateTime

The ParseExact Method from the [datetime] class has 3 formats:

Specify a single date/time format to parse:

      ::ParseExact(date_string_to_parse, Format_String, IFormatProvider)

Specify a single date/time format to parse with additional style elements:

      ::ParseExact(date_string_to_parse, Format_String, IFormatProvider, DateTimeStyles)

Specify an array of formats:

      ::ParseExact(date_string_to_parse, Format_String[], IFormatProvider, DateTimeStyles)

      The format of the string representation must match at least one of the specified Format_Strings exactly
      or an exception is thrown.

Key
   date_string_to_parse  A string that contains a date/time to convert.

   Format_String   A format specifier that defines the required format of date_string_to_parse.
                   A list of the accepted format strings.

   IFormatProvider An object that supplies culture-specific format information about date_string_to_parse.
                   For date/time values this can be a valid format string, or in most cases left as $null.

   DateTimeStyles  A bitwise combination of the enumeration values that provides additional information
                   about style elements that may be present in date_string_to_parse, or about
                   the conversion from date_string_to_parse to a DateTime value.
                   A typical value to specify is None.

Examples

Parse a date in the format yyyy-MM-dd where month and day have a leading zero:

PS C:\> $demostring = "2027-08-31"
PS C:\> $mydate = [DateTime]::ParseExact($demostring, "yyyy-MM-dd", $null)
PS C:\> $mydate

When a date is available in a standard (ISO 8601) format this can be done simply using Get-Date:

PS C:\> $mydate = Get-Date -date "2027-08-31"

Parse a date/time in the format yyyy-MM-dd~HH:mm:

PS C:\> $demostring = "2027-08-31~14:30"
PS C:\> $mydate = [DateTime]::ParseExact($demostring, "yyyy-MM-dd~HH:mm", $null)
PS C:\> $mydate

Parse a date in the format MMMddyyyy:

PS C:\> $demostring = "Aug312027"
PS C:\> $mydate = [DateTime]::ParseExact($demostring, "MMMddyyyy", $null)
PS C:\> $mydate

“Instead of planning two and a half years ago to do what they are now trying to do, they kept putting it off from day to day, week to week, and month to month, until the conscience of America demanded action” ~ Franklin D. Roosevelt, 1932 Acceptance Speech.

Related PowerShell Cmdlets

Get-Date - Get current date and time.
New-Timespan - Create a timespan object.
DateTime.ParseExact Method - Microsoft (includes additional timespan options).


 
Copyright © 1999-2026 SS64.com
Some rights reserved