开发者

C#/.NET Date: From local to UTC

I get date data from 开发者_开发技巧a user. That data is a date (e.g. 4/23/2011) and an hour (0 - 23), representing the time. This date/time that the user selects is a local time.

I need to convert this to a UTC DateTime. I have their GMTOffset for their location. 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.

From there, conversions to/from UTC are a breeze, as the offset is embedded in the structure and not dependent on local system settings.

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").


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.


Just use the DateTime.ToUniversalTime in C#, will that do what you want?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜