Powershell v5 中的字符串到日期时间转换错误

String to datetime conversion error in Powershell v5

我有 2 行代码有问题,它们没有按我预期的那样工作。关键是 DateTime 对象被转换为 string 并返回 DateTime,使用默认转换,没有明确的格式规范。

$timeString = [DateTime]::Now.ToString() # contains 17.01.2017 20:01:30
$time = [DateTime]$timeString # PS blows with error

所以,基本上,它使用默认的日期格式来格式化字符串,但它似乎使用其他格式来解析它。但是,以下代码行将起作用:

$otherTime = [DateTime]"01/17/2017 20:01:30" # will get the initial date

有人可以指点我有关类型转换问题的正确文档吗?为什么在这种情况下它会使用不同的格式来回转换数据?

提前致谢。

您正在隐式调用 Convert.ToDateTime(String),但此方法的有效格式是硬编码的(并且似乎未列出)。从您的输出日期格式来看,我发现您可能不在美国,这可能是大多数格式的重点。

相反,您可以明确地使用 Convert.ToDateTime(String, IFormatProvider) 来告诉它您想要哪种文化格式提供程序。

[Convert]::ToDateTime($timeString, [System.Globalization.DateTimeFormatInfo]::CurrentInfo)

我使用的是美国系统,所以我不确定这是否可行。

您也可以使用 [DateTime]::TryParse() or [DateTime]::TryParseExact() 来明确指定您想要的格式。

解析日期总是一场噩梦。特别是如果你生活在世界上一个叫做 'outside US' 的小地方 :)

一般而言,.NET 中的日期格式设置和解析(以及许多其他字符串比较)由区域性设置控制。在某些情况下,默认行为是使用当前的文化设置。 Convert.ToDateTime就是其中之一。如果您查看文档 (Convert.ToDateTime Method (String)),它说:

If value is not null, the return value is the result of invoking the DateTime.Parse method on value using the formatting information in a DateTimeFormatInfo object that is initialized for the current culture. The value argument must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo topic.

这就是它从本地化日期字符串转换的原因。在其他情况下,默认行为是使用“Invariant Culture”设置,这通常意味着“US settings”。大多数方法都已重载并且可以采用指定应使用的区域性的参数,但它需要对 .NET 文档进行一些搜索。

根据经验:如果不会向最终用户显示,请勿使用已本地化的字符串。始终尝试找到该方法的 'Invariant Culture' 变体,并将其用于格式化和解析字符串。它将使您免于许多头痛。