Windows 10
A Microsoft operating system that runs on personal computers and tablets.
11,908 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I keep getting "Exception calling "ParseExact" with "3" argument(s): "String 'Oct 31 04:53:31 2024' was not recognized as a valid DateTime.""
when trying to parse "Thu Oct 31 04:53:31 +0100 2024"
this doesn't happen with other dates.
Code (Powershell 7.4.5):
$dateString = "Thu Oct 31 04:53:31 +0100 2024"
# Remove the day of the week and timezone
$intermediateDateString = $dateString -replace '^\w{3} ', '' -replace ' \+\d{4} ', ' '
# Parse the intermediate date string
$FileCreateDate = [datetime]::ParseExact($intermediateDateString, "MMM dd HH:mm:ss yyyy", $null).ToString("dd-MM-yyyy HH:mm:ss")
Write-Output "output dateString: $FileCreateDate"
Fixed:
$dateString = "Thu Oct 31 04:53:49 +0100 2024"
# Remove the day of the week and timezone
$intermediateDateString = $dateString -replace '^\w{3} ', '' -replace ' \+\d{4}', ''
# Parse the intermediate date string
try {
$parsedDate = [datetime]::ParseExact($intermediateDateString, "MMM dd HH:mm:ss yyyy", [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None)
# Convert to the desired format
$FileCreateDate = $parsedDate.ToString("dd-MM-yyyy HH:mm:ss")
} catch {
$FileCreateDate = ""
Write-Host "Failed to parse the date string: $($intermediateDateString)"
}
Fixed:
$dateString = "Thu Oct 31 04:53:49 +0100 2024"
# Remove the day of the week and timezone
$intermediateDateString = $dateString -replace '^\w{3} ', '' -replace ' \+\d{4}', ''
# Parse the intermediate date string
try {
$parsedDate = [datetime]::ParseExact($intermediateDateString, "MMM dd HH:mm:ss yyyy", [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None)
# Convert to the desired format
$FileCreateDate = $parsedDate.ToString("dd-MM-yyyy HH:mm:ss")
} catch {
$FileCreateDate = ""
Write-Host "Failed to parse the date string: $($intermediateDateString)"
}