简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM