I have not been able to figure out the date format to detect the date string of August 20, 2022 I have attempted using this format month dd, yyyy to detect it however it is not working. I have several dates in my file formatted in this manner. Currently my script is missing these and I need to first figure out how to detect these.
In the below code I have a date format array I pass into TryParseExact named $formatsDelimited. All of my date formats work except for the one I stated above. It is the last format string I added to the array (granted this one is not a delimited format but nonetheless … ).
The code
$formatsDelimited = [string[]]@('M_d_yyyy','M_dd_yyyy','MM_d_yyyy','MM_dd_yyyy','M_d_yy','M_dd_yy','MM_d_yy','MM_dd_yy'
,'M/d/yyyy','M/dd/yyyy','MM/d/yyyy','MM/dd/yyyy','M/d/yy','M/dd/yy','MM/d/yy','MM/dd/yy'
,'M-d-yyyy','M-dd-yyyy','MM-d-yyyy','MM-dd-yyyy','M-d-yy','M-dd-yy','MM-d-yy','MM-dd-yy'
,'M.d.yyyy','M.dd.yyyy','MM.d.yyyy','MM.dd.yyyy','M.d.yy','M.dd.yy','MM.d.yy','MM.dd.yy'
,'month dd, yyyy')
@(
'January 21, 2019'
'05_11_2022'
'NULL'
'6/15/2020 6/16/2020'
'7/'
'09.01.2022'
'02262021'
'05/04/2021'
'ES'
'10/11'
'10/15'
'03/202022'
'10202022'
'Last week'
'10/06//2022'
'3/8/22'
'July 28, 2022'
'August 20, 2022'
) |
ForEach-Object {
# Variable for date
[datetime]$dt = New-Object DateTime
# Check that directory name could be parsed to DateTime
if ([DateTime]::TryParseExact($_, $formatsDelimited,
[System.Globalization.CultureInfo]::InvariantCulture,
[System.Globalization.DateTimeStyles]::None,
[ref]$dt))
{
$_
} else {
Write-Warning "Unrecognized timestamp: $_"
}
}
Output
WARNING: Unrecognized timestamp: January 21, 2019
05_11_2022
WARNING: Unrecognized timestamp: NULL
WARNING: Unrecognized timestamp: 6/15/2020 6/16/2020
WARNING: Unrecognized timestamp: 7/
09.01.2022
WARNING: Unrecognized timestamp: 02262021
05/04/2021
WARNING: Unrecognized timestamp: ES
WARNING: Unrecognized timestamp: 10/11
WARNING: Unrecognized timestamp: 10/15
WARNING: Unrecognized timestamp: 03/202022
WARNING: Unrecognized timestamp: 10202022
WARNING: Unrecognized timestamp: Last week
WARNING: Unrecognized timestamp: 10/06//2022
3/8/22
WARNING: Unrecognized timestamp: July 28, 2022
WARNING: Unrecognized timestamp: August 20, 2022
>Solution :
You can use MMMM dd, yyyy to parse dates in that format:
'July 28, 2022', 'August 20, 2022' | ForEach-Object {
[datetime]::ParseExact($_, 'MMMM dd, yyyy', [cultureinfo]::InvariantCulture)
}
As aside, Get-Date has no problems interpreting dates with this format:
Get-Date 'July 28, 2022'