如何将 powershell UTC 日期时间对象转换为 EST
How to convert powershell UTC datetime object to EST
我收到了日期时间字符串,格式如下:
2017-08-03T12:30:00.000Z
我需要能够将这些转换为 EST。我尝试过的每个函数都会抛出一个或另一个错误,通常是:
"String was not recognized as a valid DateTime."
我试过以下变体:
$time = '2017-08-03T12:30:00.000Z'
[datetime]$datetime = $time
$culture = [Globalization.CultureInfo]::InvariantCulture
[DateTime]::ParseExact($datetime, 'MM-dd-yyyy HH:mm:ss', $culture)
我认为这与我引用的日期时间字符串如何具有 **T**
然后是 UTC 时间有关,但不知道该怎么做。也许我应该解析出时间,转换它然后重新附加到字符串的第一部分,日期,并将它们组合在一起以获得最终输出?似乎工作量太大,解决方案可能会在未来导致潜在的错误。
您应该能够简单地将祖鲁时间字符串转换为 DateTime
值。但是,结果值将采用当地时间,因此您应该将其转换回 UTC 以供进一步计算:
$timestamp = '2017-08-03T12:30:00.000Z'
$datetime = ([DateTime]$timestamp).ToUniversalTime()
然后你可以使用 TimeZoneInfo
class 将 UTC 时间戳转换为所需的时区:
[TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($datetime, 'Eastern Standard Time')
使用 [TimeZoneInfo]::GetSystemTimeZones() | Select-Object Id, DisplayName
获取可识别时区的列表。
尝试使用 [System.TimeZoneInfo]
的静态 ConvertTimeBySystemTimeZoneId()
方法 class:
$time = '2017-08-03T12:30:00.000Z'
$result = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $time), 'Eastern Standard Time')
返回的 $result 是 [DateTime]
.
顺便说一句,如果您需要将其转换回来,方法如下:
Get-Date -Date $result -Format FileDateTimeUniversal
希望这对您有所帮助。
我收到了日期时间字符串,格式如下:
2017-08-03T12:30:00.000Z
我需要能够将这些转换为 EST。我尝试过的每个函数都会抛出一个或另一个错误,通常是:
"String was not recognized as a valid DateTime."
我试过以下变体:
$time = '2017-08-03T12:30:00.000Z'
[datetime]$datetime = $time
$culture = [Globalization.CultureInfo]::InvariantCulture
[DateTime]::ParseExact($datetime, 'MM-dd-yyyy HH:mm:ss', $culture)
我认为这与我引用的日期时间字符串如何具有 **T**
然后是 UTC 时间有关,但不知道该怎么做。也许我应该解析出时间,转换它然后重新附加到字符串的第一部分,日期,并将它们组合在一起以获得最终输出?似乎工作量太大,解决方案可能会在未来导致潜在的错误。
您应该能够简单地将祖鲁时间字符串转换为 DateTime
值。但是,结果值将采用当地时间,因此您应该将其转换回 UTC 以供进一步计算:
$timestamp = '2017-08-03T12:30:00.000Z'
$datetime = ([DateTime]$timestamp).ToUniversalTime()
然后你可以使用 TimeZoneInfo
class 将 UTC 时间戳转换为所需的时区:
[TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($datetime, 'Eastern Standard Time')
使用 [TimeZoneInfo]::GetSystemTimeZones() | Select-Object Id, DisplayName
获取可识别时区的列表。
尝试使用 [System.TimeZoneInfo]
的静态 ConvertTimeBySystemTimeZoneId()
方法 class:
$time = '2017-08-03T12:30:00.000Z'
$result = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $time), 'Eastern Standard Time')
返回的 $result 是 [DateTime]
.
顺便说一句,如果您需要将其转换回来,方法如下:
Get-Date -Date $result -Format FileDateTimeUniversal
希望这对您有所帮助。