Omkar
Omkar

Reputation: 2149

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

I am working on .Net Compact Frmework(CF) application. 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?

Upvotes: 1

Views: 2928

Answers (3)

Igor  Lozovsky
Igor Lozovsky

Reputation: 2415

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.

Upvotes: 3

Hans Passant
Hans Passant

Reputation: 941208

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.

Upvotes: 3

AAT
AAT

Reputation: 3386

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

Upvotes: 5

Related Questions