c# - Windows/C# 通过操作系统(不是 IP 地址)检测用户的半球?

标签 c# .net windows geolocation

我有一个 C# .Net (4.0) 应用程序,我想根据季节为它做一些逻辑。此应用程序将由北半球和南半球的人们使用,并且可能在也可能不在连接到 Internet 的机器上使用。

另一个 SO 用户提出了类似的问题 here ,这让我可以根据机器的本地时区信息寻求解决方案。我的 JavaScript 到 C# 的“端口”大致如下所示:

        TimeZoneInfo tzi = TimeZoneInfo.Local;

        TimeSpan january = tzi.GetUtcOffset(new DateTime(System.DateTime.Now.Year, 1, 1));
        TimeSpan july = tzi.GetUtcOffset(new DateTime(System.DateTime.Now.Year, 7, 1));

        TimeSpan diff = january - july;

        if (diff.TotalDays > 0)
        {
            Console.WriteLine(tzi.DisplayName + " is in the Southern hemisphere");
        }
        else
        {
            Console.WriteLine(tzi.DisplayName + " is in the Northern hemisphere");
        }

我机器的时区恰好在北半球,正确输出:

(UTC-06:00) Central Time (US & Canada) is in the Northern hemisphere

如果我换掉这条线:

TimeZoneInfo tzi = TimeZoneInfo.Local;

我知道时区在南半球,它看起来也很有希望:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Cen. Australia Standard Time");

输出:

(UTC+09:30) Adelaide is in the Southern hemisphere

到目前为止一切顺利。但是这个技巧只有在 timezoneinfo observes daylight savings time 时才有效。 .这导致:

> (UTC+09:30) Adelaide is in the Southern hemisphere
> (UTC+09:30) Darwin is in the Northern hemisphere
> (UTC+10:00) Brisbane is in the Northern hemisphere
> (UTC+10:00) Canberra, Melbourne, Sydney is in the Southern hemisphere

我想我可以暴力破解 timezoneinfo/string 的静态字典并对它们全部进行硬编码,但我希望有一种更优雅的方法。

最佳答案

一个好的方法可能是使用地理定位(如果可用)。对于连接到 Internet 的用户,这将为您带来良好的结果。对于未连接到 Internet 的用户,您的时区解决方案会很有效。不幸的是,我认为你必须制作一个静态字典来处理不使用夏令时的时区。

时区有时是出于任意政治原因而设置的,这使得很难以完全统一的方式将它们用于此类事情。

关于c# - Windows/C# 通过操作系统(不是 IP 地址)检测用户的半球?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17170167/

相关文章:

c# - 如何垂直自动调整 winforms datagridview 控件的大小,使其行始终可见

C# ZedGraph 在设置自定义值后将 yaxis max 设置为默认值

.net - 如何防止 'bad' 实现使 MEF 中的 GetExportedValues 中毒?

.net - 有哪些方法可用于在 Storyboard Animations 中使用非固定值?

windows - 如何计算在windows批处理中编码的sha1 base64?

c# - 是否可以在 visual studio 2013 update 2 中创建一个新的 windows phone 8 项目?

c# - 如何隐藏派生类的扩展方法?

c# - 如何在应用程序中使用引用同一 dll 的不同版本的两个 dll?

c# - 最小化WPF中的窗口?

windows - Globals.Ribbons 在 Outlook 加载项启动时为空?