PowerShell: How to Convert String to Datetime


You can use the following syntax in PowerShell to convert a string variable to a datetime:

$my_date = [DateTime]"10/15/2023"

This particular example converts the string “10/15/2023” to a datetime variable named $my_date.

By using [DateTime] we are able to convert the string that comes after it into a datetime variable.

The following example shows how to use this syntax in practice.

Example: How to Convert String to Datetime Using PowerShell

Suppose we would like to convert the string “10/25/2023” to a datetime variable.

We can use the following syntax to do so:

$my_date = [DateTime]"10/15/2023"

The following screenshot shows how to use this syntax in practice:

PowerShell convert string to datetime

We can see that the string “10/15/2023” has been converted to a datetime.

It’s worth noting that [DateTime] can also handle dates in a variety of formats.

For example, suppose that we would like to convert the string “Oct 15 2023” to a datetime variable.

We can use the following syntax to do so:

$my_date = [DateTime]"Oct 15 2023"

The following screenshot shows how to use this syntax in practice:

We can see that the string “Oct 15 2023” has been converted to a datetime.

Also note that we can use ToString() to format the datetime in any way that we would like.

For example, we can use the following syntax to convert the string “Oct 15 2023” to a datetime variable and then format it to be shown as yyyy-MM-dd:

$my_date = [DateTime]"Oct 15 2023"
$my_date.ToString("yyyy-MM-dd")

The following screenshot shows how to use this syntax in practice:

PowerShell convert string to datetime with specific format

Notice that we’ve successfully converted the string “Oct 15 2023” to a datetime variable and then formatted it to be shown as 2023-10-15.

Note: Feel free to use whatever format you would like within the ToString() method.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

How to Get Month Name in PowerShell
How to Get Date Without Time in PowerShell
How to Calculate Date Difference in PowerShell

Leave a Reply