The single-argument [datetime]::Parse()
overload - e.g.,
[datetime]::Parse('21-3-2021')
- implicitly uses the date/time formats of the current culture[1], as reflected in $PSCulture
and Get-Culture
, and it seems that that current culture in effect for you doesn't recognize a date string such as '21-3-2021'
.
A simple solution is to explicitly specify a culture in which such a date format is valid and pass that culture as the second argument:
# The German culture supports such a format.
# Sample output is from my en-US (US English system).
PS> [datetime]::Parse('21-3-2021', [cultureinfo] 'de-DE')
Sunday, March 21, 2021 12:00:00 AM
If you had a truly exotic format not recognized by any of the predefined cultures (which isn't the case here), you could use the [datetime]::ParseExact()
method:
PS> [datetime]::ParseExact('21-3-2021', 'd\-M\-yyyy', [cultureinfo]::InvariantCulture)
Sunday, March 21, 2021 12:00:00 AM
Note:
The -
instances are \
-escaped to ensure that they are matched verbatim in the input; by default, they are treated as abstract placeholders for any of the date-component separators supported by the target culture.
The specific culture context passed as the 3rd argument - the invariant culture here - would only matter if the input string contained abstract placeholders and/or culture-specific month names, such as "März" for March; you can pass $null
to use the current culture.
[1] Note that if you cast a string to a type in PowerShell - e.g., [datetime] '1/13'
- the invariant culture is always used for parsing; in other words: [datetime] '1/13'
is equivalent to:
[datetime]::Parse('1/13', [cultureinfo]::InvariantCulture)
.
The invariant culture is derived from the US-English culture and is designed to be both independent of the current culture and to be stable over time, which makes it suitable for programmatic use - see this answer for more.