开发者

TimeZoneInfo|GetUtcOffset: A better solution?

I'm facing an issue wherein my server expects datetime objects in GMT format and my UI application always creates and manipulates all datetime objects according to local culture.I cannot change the culture as there are other functionalities which need the datetime objects to be according to the local format. I have written a converter for this, not sure whether there is any off the shelf api which allows me to do this.Also bit confused about the GetUtcOffset method on timezoneinfo, does it give the difference between the local time and gmt time?I tried the documentation availiable on msdn, was bit crptic for me.Please can you help?Also how do I unit test it, by changing the culture and verifying the output?

The below class converts the date time objects to contain an equivalent of GMT time, and also converts it back while receiving from the server.

Note:Both my server and the UI runs on CET time, however these datetime objects are UK specific and hence the server needs them in GMT.

public class GmtConverter : IDateConverter
    {
        private readonly TimeZoneInfo timeZoneInfo;

        public GmtConverter()
            : this(TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"))
        {

        }
        public GmtConverter(TimeZoneInfo timeZoneInfo)
        {
            this.t开发者_运维问答imeZoneInfo = timeZoneInfo;
        }

        public DateTime Convert(DateTime localDate)
        {
            var utcOffset = timeZoneInfo.GetUtcOffset(localDate);

            var unSpecified = localDate + utcOffset;

            return DateTime.SpecifyKind(unSpecified, DateTimeKind.Unspecified);  
        }

        public DateTime ConvertBack(object local)
        {
            var localDate = (DateTime) local;

            var utcOffset = timeZoneInfo.GetUtcOffset(localDate);

            var unSpecified = localDate - utcOffset;

            return DateTime.SpecifyKind(unSpecified, DateTimeKind.Unspecified);            
        }
    }


When you say GMT, do you mean UTC ? From Wikipedia:

In casual use, when fractions of a second are not important, Greenwich Mean Time (GMT) can be considered equivalent to UTC or UT1. Saying "GMT" often implies either UTC or UT1 when used within informal or casual contexts. In technical contexts, usage of "GMT" is avoided; the unambiguous terminology "UTC" or "UT1" is preferred.

If so, the problem is solved:

  • DateTime.ToUniversalTime
  • DateTime.ToLocalTime
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜