1
votes

I am trying to take a date that I am receiving from a Linux system as a string in the format yyyy/MM/dd/hh/mm/ss and I would like to convert it into a datetime PowerShell object. I have tried using the ParseExact method but appear to be missing something here because I keep getting the message that the DateTime format is not valid. Maybe I am going about this the wrong way completely. Any suggestions?

$DateTimeObject = [datetime]::ParseExact('2018/05/21/14/08/17',"yyyy/MM/dd/hh/mm/ss",$null)

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime." At line:1 char:1 + [datetime]::ParseExact('2018/05/21/14/08/17',"yyyy/MM/dd/hh/mm/ss",$n ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : FormatException

2

2 Answers

10
votes

Your date string has 14 for the hour, which is using 24-hour time. hh however only supports hours in the range 01-12. You need to use an uppercase HH instead:

$DateTimeObject = [datetime]::ParseExact('2018/05/21/14/08/17',"yyyy/MM/dd/HH/mm/ss",$null)
#                                                                          ^^

You can find a list of all valid format codes here.

0
votes

You could write your own parsing function:

function ConvertTo-DateTime([string] $datetime) {
    $arr = $datetime -split '/'
    return [datetime](($arr[0..2] -join '-'), ($arr[3..5] -join ':') -join ' ')
}