2

I have different types of date formats like MM/d/yyyy, MM/dd/yyyy etc.. I want to parse the different formats of string value to datetime in PowerShell.

[string[]]$format = @("MM/d/yyyy hh:mm:ss tt","M/d/yyyy hh:mm:ss tt","MM/dd/yyyy hh:mm:ss tt","M/dd/yyyy hh:mm:ss tt")

$dateString = "11/8/2017 02:40:31 PM"

Write-Host ([datetime]::ParseExact($dateString, $format, $null))

when I'm executing above lines I'm getting below exception

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:5 char:1
+ Write-Host ([datetime]::ParseExact($dateString, $format, $null))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

I want to parse string value to datetime and the string is can be in any format. Can anyone tell me how to achieve this using PowerShell. Thanks in advance.

beatcracker
  • 6,714
  • 1
  • 18
  • 41
sandeep
  • 53
  • 7

1 Answers1

3

This code works, although I didn't find a way to make it work with that specific overload of DateTime.ParseExact().

[string[]] $format = @("MM/d/yyyy hh:mm:ss tt","M/d/yyyy hh:mm:ss tt","MM/dd/yyyy hh:mm:ss tt","M/dd/yyyy hh:mm:ss tt")
$dateString = "11/8/2017 02:40:31 PM"

$result = $null
$format.ForEach({ [DateTime] $dt = New-Object DateTime; if([datetime]::TryParseExact($dateString, $_, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref] $dt)) { $result = $dt } });

Write-Host ($result)

Output:

11/8/2017 2:40:31 PM
sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40