如何将powershell UTC日期时间对象转换为EST
我输入了日期时间字符串,格式如下:如何将powershell UTC日期时间对象转换为EST,powershell,date,datetime,timezone,utc,Powershell,Date,Datetime,Timezone,Utc,我输入了日期时间字符串,格式如下: 2017-08-03T12:30:00.000Z 我需要能够将这些转换为EST。我尝试的每个函数都会抛出一个或另一个错误,通常是: “字符串未被识别为有效的日期时间。” 我已经尝试了以下的变体: $time = '2017-08-03T12:30:00.000Z' [datetime]$datetime = $time $culture = [Globalization.CultureInfo]::InvariantCulture [DateTime]::P
2017-08-03T12:30:00.000Z
我需要能够将这些转换为EST。我尝试的每个函数都会抛出一个或另一个错误,通常是:
“字符串未被识别为有效的日期时间。”
我已经尝试了以下的变体:
$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时间有关,但我不知道该怎么做。也许我应该解析出时间,转换它,然后重新附加到字符串的第一部分,日期,并将它们组合在一起以获得最终输出?似乎工作量太大,解决方案可能会在将来导致潜在错误。您应该能够通过简单地将Zulu时间字符串转换为DateTime
值。但是,结果值将以当地时间为单位,因此您应将其转换回UTC进行进一步计算:
$timestamp = '2017-08-03T12:30:00.000Z'
$datetime = ([DateTime]$timestamp).ToUniversalTime()
然后,您可以使用该类将UTC时间戳转换为所需的时区:
[TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($datetime, 'Eastern Standard Time')
使用
[TimeZoneInfo]::GetSystemTimeZones()|选择对象Id,DisplayName
以获取已识别时区的列表。您应该能够通过强制转换将Zulu时间字符串转换为日期时间值。但是,结果值将以当地时间为单位,因此您应将其转换回UTC进行进一步计算:
$timestamp = '2017-08-03T12:30:00.000Z'
$datetime = ([DateTime]$timestamp).ToUniversalTime()
然后,您可以使用该类将UTC时间戳转换为所需的时区:
[TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($datetime, 'Eastern Standard Time')
使用[TimeZoneInfo]::GetSystemTimeZones()|选择对象Id,DisplayName
以获取已识别时区的列表。尝试使用[System.TimeZoneInfo]
类的静态ConvertTimeBySystemTimeZoneId()
方法:
$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
希望这有帮助。尝试使用[System.TimeZoneInfo]
类的静态ConvertTimeBySystemTimeZoneId()
方法:
$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
希望这有帮助。您需要将ParseExact更改为变量中的日期时间格式[DateTime]::ParseExact($DateTime,'MM/dd/yyyy HH:MM:ss',$culture)
注意“/”而不是“-”,这不会引发任何错误。这就是您想要的吗?您需要将ParseExact更改为变量中的日期时间格式[DateTime]::ParseExact($DateTime,'MM/dd/yyyy HH:MM:ss',$culture)
注意“/”而不是“-”,这不会引发任何错误。这就是你要找的吗?