开发者

Changing TimeZone does not reflect change in Time in .NET Compact Framework

开发者 https://www.devze.com 2023-04-01 02:46 出处:网络
I am working on .Net Compact Frmework(CF) appli开发者_如何转开发cation. I this application the requirement is that I should be able to change the TimeZone. However, when I changed the TimeZone the cur

I am working on .Net Compact Frmework(CF) appli开发者_如何转开发cation. I this application the requirement is that I should be able to change the TimeZone. However, when I changed the TimeZone the current time does not changed to that particular TimeZone. From, web I came to know that DateTime.Now can not work in this case.

I am using following Win API:

  1. SetTimeZoneInformation(...) - To set the time zone at Runtime.
  2. GetLocalTime(...) - To get the Local time w.r.t current time zone.

Can anybody tell me what might be wrong?


Changing the timezone from an application in this way does not change the Local Time: instead it changes the System Time in order to keep the Local Time the same. This is not what the Control Panel does, but if you want to emulate the Control Panel functionality you need to do something like this:

  • save the System Time
  • change the Time Zone
  • restore the saved System Time

That way the System Time stays the same and the Local Time changes according to the selected time zone.

By the way we do this in one of our products using the OpenNETCF library (http://www.opennetcf.com), which includes a DateTimeHelper class (amongst many other useful things -- and the community edition is free). (That's just a little neater than writing your own pinvoke to access SetTimeZoneInformation(), the functionality is the same.)


This is by design, it avoids code that depends on a steadily increasing clock from suffering a heart attack. The workaround is to call CultureInfo.CurrentCulture.ClearCachedData() explicitly after changing the time zone. Or restart the app.


I have the same issue. In my case to change TimeZone without changing time, I used this code:

DateTime dateTime = DateTime.Now;
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
TimeSpan currentOffset = timeZone.BaseUtcOffset.Duration();
DateTimeOffset offset = new DateTimeOffset(dateTime, currentOffset);

I have GMT+2 TimeZone. For example 11/7/2012 14:00 +02:00.

After using this code I have GMT+1 with the same time. 11/7/2012 14:00 +01:00.

0

精彩评论

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

关注公众号