如何将 powershell UTC datetime 对象转换为 EST [英] How to convert powershell UTC datetime object to EST

查看:45
本文介绍了如何将 powershell UTC datetime 对象转换为 EST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我输入了日期时间字符串,格式如下:

I have date time strings coming in, formatted like the following:

2017-08-03T12:30:00.000Z

我需要能够将这些转换为 EST.我尝试过的每个函数都会抛出一个或另一个错误,通常是:

I need to be able to convert these to EST. Every function I have tried throws one error or another, typically being:

字符串未被识别为有效的日期时间."

我尝试了以下变体:

$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 时间有关,但不知道该怎么做.也许我应该解析时间,转换它,然后重新附加到字符串的第一部分,日期,并将它们组合在一起以获得最终输出?似乎工作量太大,而解决方案可能会导致将来出现潜在错误.

I think it has something to do with how the Date Time string I am referencing has the **T** and then the UTC time, but can't figure out what to do about it. Maybe I should parse out the time, convert it and then reattach to the first part of the string, the date, and combine them together for the final output? Seems like way too much work and a solution which would cause potential errors in the future.

推荐答案

您应该能够通过简单地将 Zulu 时间字符串转换为 DateTime 值.但是,结果值将采用当地时间,因此您应该将其转换回 UTC 以进行进一步计算:

You should be able to convert a Zulu time string to a DateTime value simply by casting it. However, the resulting value will be in local time, so you should convert it back to UTC for further calculations:

$timestamp = '2017-08-03T12:30:00.000Z'
$datetime  = ([DateTime]$timestamp).ToUniversalTime()

然后您可以使用TimeZoneInfo 类将 UTC 时间戳转换为所需的时区:

Then you can use the TimeZoneInfo class to convert the UTC timestamp to the desired timezone:

[TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($datetime, 'Eastern Standard Time')

使用[TimeZoneInfo]::GetSystemTimeZones() |Select-Object Id, DisplayName 以获取已识别时区的列表.

Use [TimeZoneInfo]::GetSystemTimeZones() | Select-Object Id, DisplayName to get a list of the recognized timezones.

这篇关于如何将 powershell UTC datetime 对象转换为 EST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆