Empty Coder
Empty Coder

Reputation: 589

Convert date and time string to datetime format

I am developing a powershell application where i am taking input date and time as string.

Need to find the difference after that.

But when i am trying to convert the string to datetime i am getting error. Below is the code and the error

    $TimeFrom = "27-08-2020 15:13:32 PM"
    $TimeFrom = [datetime]::parseexact($TimeFrom, 'dd-MM-yyyy HH:mm:ss tt ', $null)
    $TimeTo   = "27-08-2020 15:30:32 PM"
    $TimeTo = [datetime]::parseexact($TimeFrom, 'dd-MM-yyyy HH:mm:ss tt ', $null)

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."

Please let me know on this.

Upvotes: 0

Views: 228

Answers (1)

Ash
Ash

Reputation: 3246

You have an extra space after tt and the second conversion is reusing $TimeFrom.

$TimeFrom = "27-08-2020 15:13:32 PM"
$TimeFrom = [datetime]::parseexact($TimeFrom, 'dd-MM-yyyy HH:mm:ss tt', $null)
$TimeTo   = "27-08-2020 15:30:32 PM"
$TimeTo = [datetime]::parseexact($TimeTo, 'dd-MM-yyyy HH:mm:ss tt', $null)
$TimeFrom
$TimeTo

Upvotes: 1

Related Questions