Parse Datetime by ParseExact in PowerShell

  1. Use the ParseExact Method to Parse DateTime in PowerShell
  2. Use the Explicit Type Conversion to Parse DateTime in PowerShell

While working with dates on PowerShell, there are times when you will need to convert the date string to a DateTime object. You cannot use date strings to perform DateTime operations; you will need the DateTime object.

This tutorial will teach you to parse and convert strings to DateTime format in PowerShell.

Use the ParseExact Method to Parse DateTime in PowerShell

The ParseExact method of the DateTime class converts the date and time string to the DateTime format. The format of a date and time string patterns must match the specified format of the DateTime object.

The following example converts the date string to a DateTime object using the ParseExact method.

$strDate = '2022/06/11'
[DateTime]::ParseExact($strDate, 'yyyy/MM/dd', $null)

In the above script, the string of a date is stored in a variable $strDate. Then it is passed to the ParseExact method followed by the DateTime format, which matches the pattern of the date string.

Output:

11 June 2022 00:00:00

You can store the converted DateTime format in a variable and check the data type using the GetType() method.

$strDate = '2022/06/11'
$newDate=[Datetime]::ParseExact($strDate, 'yyyy/MM/dd', $null)
$newDate.GetType()

Output:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     DateTime                                 System.ValueType

Use the Explicit Type Conversion to Parse DateTime in PowerShell

You can also cast the string of a date and time to the DateTime format in PowerShell.

Using this syntax, you can cast a string to the DateTime object.

[DateTime]string

The following example converts the string representation of a date and time to the DateTime object with the cast expression.

$strDate = "2022-06-11 09:22:40"
[DateTime]$strDate

Output:

11 June 2022 09:22:40

With the DateTime object, you should be able to perform any DateTime operations. We hope this tutorial helps you understand how to convert strings to the DateTime format in PowerShell.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - PowerShell DateTime

  • Get Date and Time Using PowerShell
  • Convert a String to Datetime in PowerShell