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

标签 powershell datetime powershell-5.0

我有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/

相关文章:

powershell - 显示当前正在执行的函数名称

powershell - Windows 期望命令等效

powershell - Route53 - 创建 TXT 类型 dns 记录时出错 (powershell)

ruby-on-rails - 为 '/edit' View 填充表单字段时,Rails 应用程序 config.time_zone 不适用

php - 难以以小时计算年龄

powershell - 最大化窗口并使用Powershell将其置于最前面

java - DateTimeParseException : Text '2019-08-13T07:29:12.000+0000' could not be parsed, 在索引 23 处找到未解析的文本

powershell - 使用 -PathType 参数如何影响 Test-Path 的效率?

powershell - 为数组中的所有对象转换属性的数据类型

.net - 为什么不能在PowerShell中的事件处理程序中设置表单的DialogResult?