简体   繁体   English

从字符串捕获UTC时间并将其格式化为所有DateTime

[英]Capture UTC Time From String And Format All DateTime To It

I have a date that is being returned in a string format 我有一个以字符串格式返回的日期

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

How could I extract the 07:00 Mountain Time from the string above and format any date to this regional formatting? 如何从上面的字符串中提取山区时间07:00并将任何日期格式化为该区域格式?

I do not want to change timezones on my computer, as the UTC time returned to the variable utcdt can vary depending, and all other dates used in my WinForm app would need to conform to the same timezone specifications. 我不想更改计算机上的时区,因为返回到变量utcdt的UTC时间可能会有所不同,并且WinForm应用程序中使用的所有其他日期都需要符合相同的时区规范。

Edit 编辑
I am using the FEDEx API and this is one format of the date returnerd 我正在使用FEDEx API,这是返回日期的一种格式

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

Now later in the application there is 现在稍后在应用程序中

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

Which returns the data in my local time - meaning 哪个返回我当地时间的数据-含义

01/01/2017 17:48:00

I am trying to come up with a solution to have the dates be consistent. 我正在尝试提出一种解决方案,以使日期保持一致。

You can use the DateTimeOffset class to parse the string into the local time and it's offset from UTC. 您可以使用DateTimeOffset类将字符串解析为本地时间,并将其与UTC进行偏移。 You can then save the offset as a TimeSpan . 然后,您可以将偏移量另存为TimeSpan

Later on then again use the DateTimeOffset class to convert another DateTime you have to use the same offset: 稍后再使用DateTimeOffset类转换另一个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"));

Note what other commentators have written: This does not correctly deal with Daylight Saving Time. 请注意其他评论者写了什么:这不能正确处理夏时制。 In order to deal with that, you actually need to know the real timezone. 为了解决这个问题,您实际上需要知道实时时区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM