1

How do I convert a string date held in a variable to a datetime format.

The variable $stringdate contains the string '2020-04-10 09:15:30' when I run the commands (1) below I get the following error:

InvalidArgument: Cannot convert value "2020-04-10 09:15:30" to type "System.DateTime"`. 
Error: "String '2020-04-10 09:15:30' was not recognized as a valid DateTime."

If I run commands (2) with the string "2020-04-10 09:15:30" instead of the variable $stringdate it doesn't error and returns 10 April 2020 09:15:30??

#(1)

$date = $stringdate
    
[datetime]$date
# (2)
    
$date ="2020-04-10 09:15:30"
    
[datetime]$date
4
  • How did you obtain/create $stringdate in the first place? Commented Jul 5, 2022 at 10:45
  • 1
    it is a string from a text file using get-content Commented Jul 5, 2022 at 11:08
  • Given that $stringdate = '2020-04-10 09:15:30'; [datetime] $stringdate works fine, the implication is that the $stringdate read from a file contains something else - perhaps invisible control characters. Commented Jul 5, 2022 at 12:14
  • To put it differently: with the information currently contained in your question, the problem is not reproducible. Commented Jul 5, 2022 at 15:14

1 Answer 1

1

You already wrote the cause for your issue in your question: You have a string not a Datetime. That is why you got an erorr. You must parse your string to a datetime object.

You can use ParseExact. If you want the format 'yyyy-MM-dd HH:mm:ss', try this:

$stringDate = "2020-04-10 09:15:30"
$dateTime = [datetime]::ParseExact($stringDate, 'yyyy-MM-dd HH:mm:ss', $null)
echo $dateTime

Output:

Friday, 10. April 2020 09:15:30

For further information: ParseExact

Sign up to request clarification or add additional context in comments.

4 Comments

thanks that works but I want to convert the string '2020-04-10 09:15:30 in the variable $stringdate to be a datetime. is there a way to do something like $date = $stringDate $dateTime = [datetime]::ParseExact($date, 'yyyy-mm-dd HH:mm:ss', $null) [datetime]$dateTime without getting the error _ Exception calling "ParseExact" with "3" argument(s): "String '2020-04-10 09:15:30' was not recognized as a valid DateTime." _
@Nivag what you are doing is correct. However, you are parsing minutes instead of Months. Use a capital "M". So instead of "mm" use "MM".
MM stands for month and mm for minutes.
While this works, there is no need for .ParseEact(): a simple [datetime] cast, as attempted in the question, is enough: $stringdate = '2020-04-10 09:15:30'; [datetime] $stringdate. Therefore, the problem must be that the $stringdate value read from a file either contains a different format or extraneous characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.