我有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
有人可以指出类型转换问题的相关文档吗?为什么在这种情况下,它将使用不同的格式来回转换数据?
提前致谢。
最佳答案
解析日期始终是一场噩梦。特别是如果您生活在被称为“美国以外”的一小部分世界:)
通常,.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.
这就是为什么它会从您本地化的日期字符串转换而来的原因。在其他情况下,默认行为是使用“不变文化”设置,这通常表示“美国设置”。大多数方法都是重载的,并且可以采用指定应该使用的区域性的参数,但是需要在.NET文档中进行一些搜索。
根据经验:如果不向最终用户显示字符串,请不要使用本地化的字符串。始终尝试找到该方法的“不变文化”变体,并将其用于格式化和解析字符串。它将使您免于许多头痛。
关于powershell - Powershell v5中的字符串到日期时间的转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705109/