C # calc time diff between 2 countries, including DST

I want to know the time difference between the two countries. Of course, there is a static time difference, but in some periods there is a switch to daylight saving time. As far as I know, the dst period is also different for some countries, so in June 1 the difference between countries a and b can be 1 hour, on July 1 it can be 2 hours due to DST, and on August 1 it can be 1 time, etc. d. etc.

Is there a framework function for it, or should I figure it out myself?

Michelle

+4
source share
2 answers

You need to know:

  • Both time zones (use TimeZoneInfo from .NET 3.5, keeping in mind that one country can have multiple time zones)
  • A moment in time, for example. UTC DateTime or DateTimeOffset .

This is relatively easy at this point: instantly convert UTC to local time in both time zones using TimeZoneInfo.ConvertTime and subtract one from the other. Alternatively, use TimeZoneInfo.GetUtcOffset for both of them and subtract one offset from the other.

Here is an example to find the current difference between London and Mountain View:

 using System; class Test { static void Main() { var mountainView = TimeZoneInfo.FindSystemTimeZoneById ("Pacific Standard Time"); var london = TimeZoneInfo.FindSystemTimeZoneById ("GMT Standard Time"); DateTimeOffset now = DateTimeOffset.UtcNow; TimeSpan mountainViewOffset = mountainView.GetUtcOffset(now); TimeSpan londonOffset = london.GetUtcOffset(now); Console.WriteLine(londonOffset-mountainViewOffset); // 8 hours } } 
+7
source

To find out any historical difference (i.e., for a date in the past when the local DST policies for one or both time zones were different), you would need to save the past policies for starting and ending DST for each time zone and work with them out of myself.

If you are good at knowing the difference based on the current set of rules loaded on Windows, then the built-in .NET method is simple and straightforward.

0
source

All Articles