Convert a String to Datetime in PowerShell

Rohan Timalsina Dec 31, 2021
  1. Use ParseExact to Convert String to DateTime in PowerShell
  2. Use the Explicit Conversion to Convert a String to DateTime in PowerShell
Convert a String to Datetime in PowerShell

String and DateTime are two different data types in PowerShell. This tutorial will introduce two methods to convert a string to DateTime in PowerShell.

Use ParseExact to Convert String to DateTime in PowerShell

The ParseExact method helps convert the specified date and time string to the DateTime data type.

We have a variable $date, which contains the date in string format.

$date = "2021/12/25"

You can check the data type using the GetType() method.

$date.GetType()

Output:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Let’s convert the string to DateTime. When converting, the date and time format in a string must match the specified format in DateTime.

Here, ParseExact converts the string date to the DateTime format yyyy/MM/dd.

$a = [datetime]::ParseExact($date, 'yyyy/MM/dd', $null)
$a

Output:

Saturday, December 25, 2021 12:00:00 AM

Now, check the data type of variable $a.

$a.GetType()

Output:

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

Use the Explicit Conversion to Convert a String to DateTime in PowerShell

We can convert a string to DateTime in PowerShell by casting it to DateTime format.

$b = [DateTime]$date
$b

Output:

Saturday, December 25, 2021 12:00:00 AM

Check the data type:

$b.GetType().Name

Output:

DateTime
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell DateTime