Home > Net >  Powershell Datetime::Parseexact with multiple formats
Powershell Datetime::Parseexact with multiple formats

Time:02-11

I am trying to use parseexact , however the dates that I have are in multiple formats. I tried

$format =@('yyMMddHHmm') 
[System.DateTime]::ParseExact('1605221412',$format,$null)

and everything is fine When I try to add another format I get an exception

$format =@('yyMMddHHmm', 'yyyyMMddHHmm') 
[System.DateTime]::ParseExact('1605221412',$format,$null,[System.Globalization.DateTimeStyles]::None)

I tried double quotes, writing inline , various ways of trying to pass an array as the second argument.

[System.DateTime]::ParseExact('1605221412','yyMMddHHmm, yyyyMMddHHmm',$null,[System.Globalization.DateTimeStyles]::None)

What am I missing ? Is it possible to use ParseExact for multiple formats without doing a bunch of if, then , else statements ?

CodePudding user response:

You are doing it just fine, the only problem is that @(..) is object[] not string[]:

$datesToTest = '1605221412', '09/02/2022', '02-09-2022'
$formats = 'yyMMddHHmm', 'yyyyMMddHHmm', 'dd/MM/yyyy', 'dd-MM-yyyy'
$datesToTest | ForEach-Object {
    [System.DateTime]::ParseExact($_, [string[]]$formats, [cultureinfo]::InvariantCulture)
}
  • Related