Reputation: 663
I am trying to parse "time" strings for comparison purposes
$Test2 =[datetime]::Parse("24/09/2015 05:41:27",[Globalization.cultureinfo]::GetCultureInfo("en-US"))
$Test2
$Test =[datetime]::Parse("23/09/2015 05:41:27",[Globalization.cultureinfo]::GetCultureInfo("en-US"))
$Test
if($Test2 -gt $Test)
write-host comparison works
I get the following error:
Exception calling "Parse" with "2" argument(s): "String was not recognized as
a valid DateTime."
At C:\Users\Desktop\ne.ps1:1 char:1
+ $Test =[datetime]::Parse("23/09/2015
05:41:27",[Globalization.cultureinfo]::GetC ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FormatException
Upvotes: 2
Views: 2157
Reputation: 59328
Since /
is a culture-sensitive date separator character, another options would be:
set CultureInfo.InvariantCulture
:
[datetime]::Parse("24/09/2015 05:41:27",[Globalization.cultureinfo]::CultureInfo.InvariantCulture)
or utilize DateTime.ParseExact method
:
[datetime]::ParseExact("23/09/2015 05:41:27","dd/MM/yyyy HH:mm:ss",[Globalization.cultureinfo]::GetCultureInfo("en-US"))
Upvotes: 2
Reputation:
The en-US
culture uses the month-day-year format, so you'll want to either:
Here is a code sample:
### Change the date/time input string
[datetime]::Parse("09/23/2015 05:41:27")
### Use the Great Britain culture
[datetime]::Parse("23/09/2015 05:41:27", [cultureinfo]::GetCultureInfo('en-GB'))
Upvotes: 4