Powershell

Convert a String to DateTime in PowerShell

PowerShell is a fully-featured Windows tool used for all administrative tasks inside the system. It can style date and time in several formats. Moreover, PowerShell has the capability to convert a string to DateTime. The string and DateTime are the two different data types in PowerShell. The string is the combination of words that makes a meaningful text, while DateTime is used to represent or display date and time in PowerShell.

This tutorial will guide you about transforming a string to PowerShell’s DateTime.

How to Convert/Transform a String to PowerShell’s DateTime?

These methods can convert a string to DateTime in PowerShell:

Method 1: Convert a String to DateTime in PowerShell Using Cast String Method

The casting of the date and time string can help it convert to DateTime. More specifically, casting is used in PowerShell to convert a string to different data types, including integers or DateTime. In our case, we need to convert a string to DateTime in PowerShell.

Example

Let’s take a look at the given example to convert a string to DateTime using the Cast string method:

> $DateTimeStr = "2023-01-12"
> [DateTime]$DateTimestr

According to the code:

  • First, we created a variable and assigned the date and time string.
  • After that, we used the cased created variable in the “DateTime” format:

The output confirms that the specified string has been converted to DateTime in PowerShell.

Method 2: Convert a String to DateTime in PowerShell Using ParseExact() Method

The “ParseExact()” is the method of the “DateTime” class. It is specially designed to convert a string representation of the date and time assigned by the user to the DateTime data type.

Example

Now, execute the following code in PowerShell:

> $DateTimestr = '2023/01/12'
> [Datetime]::ParseExact($DateTimestr, 'yyyy/MM/dd', $null)

In the stated code:

  • First, we have created a variable and assigned a string date and time value to it.
  • After that, we used the “ParseExact()” method and passed the “DateTimestr” string, the required format “yyyy/MM/dd”, and “null” as arguments:

That was all about converting a string to DateTime in PowerShell.

Conclusion

The string in PowerShell can be converted into DateTime using two methods, “Cast string” and “ParseExact()”. Both of the methods first take the date and time string from the user and then convert it to the DateTime. This tutorial has presented a thorough guide to convert a PowerShell string in DateTime.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.