2

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 ?

1 Answer 1

3

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

$datesToTest = '1605221412', '09/02/2022', '02-09-2022'
[string[]] $formats = 'yyMMddHHmm', 'yyyyMMddHHmm', 'dd/MM/yyyy', 'dd-MM-yyyy'
$datesToTest | ForEach-Object {
    [datetime]::ParseExact(
        $_,
        $formats,
        [cultureinfo]::InvariantCulture,
        [System.Globalization.DateTimeStyles]::None)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Just learning Powershell now
@GoGoPuffs happy to help :)

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.