Powershell Code - ParseExact Date Conversion - String not recognized as valid DateTime
Windows Powershell
Goal: Read and validate a string-date (with a known and expected format).
Guarding against February 31st and stuff like that
Technique:
Cast the string into a [datetime].
Use ParseExact to convert the date
Use ParseExact to convert the date
Use try-catch to detect detect failures.
Code:
[DateTime]$dtconvertedDate #Declare DateTime Variable
[string]$strmyDate = "01/01/2025" #Variable to test
try
{
# Cast the ParseExact as [dateTime]
# Unsafe
[string]$strmyDate = "01/01/2025" #Variable to test
try
{
# Cast the ParseExact as [dateTime]
# Unsafe
$dtconvertedDate = [datetime]::ParseExact($strmyDate, "MM/dd/yyyy", $null)
# Safer
$dtconvertedDate = [datetime]::ParseExact($strmyDate.Trim(), "M/d/yyyy", $null)
}
# Safer
$dtconvertedDate = [datetime]::ParseExact($strmyDate.Trim(), "M/d/yyyy", $null)
}
catch
{
# not illustrated -- not a date
}
Possible errors:
# not illustrated -- not a date
}
Possible errors:
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
Possible answers:
- $strmyDate is from an Excel-exported CSV or tab file. Be sure to .Trim(). Unsafe otherwise.
- Mask "MM/dd/yyyy" is case-sensitive!
- Mask "MM/dd/yyyy" can be, but is not always safe.
Date strings with leading zeros vs not: "1/17/2025" -- MM/dd will fail.
Use "M/d/yyyy"
- Mask "MM/dd/yyyy" is case-sensitive!
- Mask "MM/dd/yyyy" can be, but is not always safe.
Date strings with leading zeros vs not: "1/17/2025" -- MM/dd will fail.
Use "M/d/yyyy"
- Mask in wrong format: MM-dd-yyyy vs MM/dd/yyyy
hyphens vs slash. ParseExact with a mask cares.
hyphens vs slash. ParseExact with a mask cares.
No comments:
Post a Comment
Comments are moderated and published upon review. (As an aside, not a single spam has been allowed through; why bother?)