.net - ParseExact,字符串无法识别

标签 .net powershell

我有以下代码:

$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/

相关文章:

c# - C# 编译器是否足够智能来优化此代码?

c# - 如何将跟踪输出发送到文件系统中的文件?

powershell - 我有一个包含数千封电子邮件的 .csv,我需要使用 Active Directory 使用 powershell 来查找特定自定义变量的状态

sql-server - 在租户中找不到 Active Directory 对象 ''

powershell - 从任务列表中传递答案以检查进程的内存使用情况,并在超过阈值时终止

c# - 我如何跟踪对数据库表的任何更改

.net - 在具有相同架构的多个数据库中使用 EF(或另一个 .NET ORM)

.net - ninject 被视为容器吗?

file - Powershell脚本用来自不同文本文件的内容替换字符串,并保持换行

powershell - 我不能 'Out-File' 我的整个循环只有一行