我有以下代码:
$timeinfo = '01 January 2015 15:05:00'
$template = 'dd MMMM yyyy HH:mm:ss'
[DateTime]::ParseExact($timeinfo,$template,$null)
当我运行它时,出现以下异常:
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At DataBase.ps1:34 char:23
+ [DateTime]::ParseExact <<<< ($timeinfo,$template,$null)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
字符串格式对我来说似乎是正确的,有什么问题吗?为什么?
最佳答案
您正在传递月份名称 January
作为要解析的字符串的一部分。如果您不传递区域性以便能够将该名称解析回月份数字,则使用当前正在执行的线程的区域性。如果不是英语那么解析将会失败。为了确保不会发生这种情况,因为无法保证线程的区域性(除非您之前明确设置),您应该传递区域性格式提供程序。
$formatProvider = [System.Globalization.CultureInfo]::GetCulture('en-US')
[DateTime]::ParseExact($timeinfo, $template, $formatProvider)
关于.net - ParseExact,字符串无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44032636/