Exception calling "ParseExact" when processing a certain date

Gabriel 0 Reputation points
2024-12-12T03:21:23.4333333+00:00

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"
Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
11,908 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,708 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Gabriel 0 Reputation points
    2024-12-19T02:19:30.15+00:00

    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)"
    }
    

  2. Gabriel 0 Reputation points
    2024-12-19T02:20:21.6333333+00:00

    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)"
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.