简体   繁体   English

C#/。NET日期:从本地到UTC

[英]C#/.NET Date: From local to UTC

I get date data from a user. 我从用户那里获得日期数据。 That data is a date (eg 4/23/2011) and an hour (0 - 23), representing the time. 该数据是一个日期(例如4/23/2011)和一小时(0-23),代表时间。 This date/time that the user selects is a local time. 用户选择的日期/时间是本地时间。

I need to convert this to a UTC DateTime. 我需要将其转换为UTC DateTime。 I have their GMTOffset for their location. 我有他们的GMTOffset的位置。 How can I do this? 我怎样才能做到这一点?

You should work with the DateTimeOffset structure , specifically, the constructor that takes the DateTime and the TimeSpan that represents the offset . 您应该使用DateTimeOffset结构 ,特别是采用DateTime构造函数和表示偏移量的TimeSpan

From there, conversions to/from UTC are a breeze, as the offset is embedded in the structure and not dependent on local system settings. 从那里,转换到UTC或从UTC转换是轻而易举的,因为偏移嵌入在结构中而不依赖于本地系统设置。

Note, even though not commonly adhered to, it is recommended to work with DateTimeOffset most of the time, as opposed to DateTime (see the note under the section titled "The DateTimeOffset Structure"). 请注意,即使不常见,但建议大多数时间使用DateTimeOffset ,而不是DateTime (请参阅标题为“DateTimeOffset结构”一节下的注释)。

var utcDateTime = 
     new DateTimeOffset(userDateTime, TimeSpan.FromHours(userUtcOffset)).UtcDateTime;

Of course you can use TimeSpan differently if the GMT offset has minutes / fractions of an hour. 当然,如果GMT偏移量具有一小时的分钟/分数,则可以使用不同的TimeSpan

只需在C#中使用DateTime.ToUniversalTime,那会做你想要的吗?

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

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