从字符串中捕获 UTC 时间并将所有日期时间格式化为它

Capture UTC Time From String And Format All DateTime To It

我有一个以字符串格式返回的日期

string utcdt = "2017-01-01T15:48:00-07:00";

如何从上面的字符串中提取 07:00 山地时间并将任何日期格式化为该区域格式?

我不想更改计算机上的时区,因为返回到变量 utcdt 的 UTC 时间可能会有所不同,并且我的 WinForm 应用程序中使用的所有其他日期都需要符合相同的时区规格。

编辑
我正在使用 FEDEx API,这是日期 returnerd

的一种格式
string utcdt = "2017-01-01T15:48:00-07:00";

现在在应用程序的后面有

foreach (TrackingDateOrTimestamp timestamp in trackDetail.DatesOrTimes)
    Console.WriteLine("{0}: {1}", timestamp.Type, timestamp.DateOrTimestamp);

其中 returns 我当地时间的数据 - 意思是

01/01/2017 17:48:00

我正在尝试想出一个使日期保持一致的解决方案。

您可以使用 DateTimeOffset class 将字符串解析为本地时间,它与 UTC 的偏移量。然后您可以将偏移量保存为 TimeSpan.

稍后再次使用 DateTimeOffset class 转换另一个 DateTime 你必须使用相同的偏移量:

string dto = "2017-01-01T15:48:00-07:00";

DateTimeOffset dateTimeOffset = DateTimeOffset.Parse(dto);

DateTime utcDateTime = dateTimeOffset.UtcDateTime;
TimeSpan timezoneOffset = dateTimeOffset.Offset;


MessageBox.Show("UTC DateTime: " + utcDateTime);
MessageBox.Show("Offset: " + timezoneOffset);

DateTimeOffset nowWithOffset = DateTimeOffset.UtcNow.ToOffset(timezoneOffset);

MessageBox.Show("Now in other timezone: " + nowWithOffset.ToString("O"));

请注意其他评论员所写的内容:这不能正确处理夏令时。为了解决这个问题,您实际上需要知道实际时区。