c# - 如何从用户 pc TimeZone 中提取当前日期和时间

标签 c#

任何人都可以建议我有什么方法可以检测英国、德国和法国的国家明智时间。我不确定,但我们能否从 datetime UTC 时间中提取国家/地区时间 DateTime.UtcNow ?

请告诉我,因为我处于用户可以从任何国家/地区登录我们的网站的情况,我需要根据他所在国家/地区的当前时间在下拉列表中显示时间。

另一个人这样做了,但我不确定我是否应该遵循他的方法。这是网址
http://www.c-sharpcorner.com/Blogs/7096/

private string GetCountryTime(string country)
    {
        DateTime gmt = default(DateTime);
        System.DateTime value = default(System.DateTime);
        gmt = DateTime.Now.AddMinutes(-330);

        switch (country)
        {
            case "India":
            case "Sri Lanka":
                return DateTime.Now.ToString();
            case "United Kingdom":
            case "Portugal":
            case "Sierra Leone":
            case "Senegal":
            case "Morocco":
            case "Mali":            
                return gmt.ToString();
            case "France":
            case "Spain":
            case "Slovenia":
            case "Slovakia":
            case "Poland":
            case "Nigeria":
            case "Niger":
            case "Hungary":
            case "Denmark":
            case "Czech Republic":
                return gmt.AddMinutes(60).ToString();
            case "Botswana":
            case "Moldova":
            case "South Africa":
            case "Malawi":
            case "Lithuania":
            case "Libya":
            case "Turkey":
            case "Finland":
            case "Egypt":
                return gmt.AddMinutes(120).ToString(); ;
            case "Bahrain":
            case "Somalia":
            case "Saudi Arabia":
            case "Russia":
            case "Qatar":
            case "Sudan":
            case "Madagascar":
            case "Iraq":
                return gmt.AddMinutes(180).ToString();
            case "Iran":
                return gmt.AddMinutes(220).ToString();
            case "Armenia":
            case "Seychelles":
            case "Reunion":
            case "Oman":
            case "Mauritius":
            case "United Arab Emirates":
            case "Georgia":
            case "Azerbaijan":
                return gmt.AddMinutes(240).ToString();
            case "Afghanistan":
                return gmt.AddMinutes(270).ToString();
            case "Pakistan":
            case "Maldives":
            case "Kyrgyzstan":
                return gmt.AddMinutes(300).ToString();
            case "Nepal":
                return gmt.AddMinutes(345).ToString();
            case "Bangladesh":
            case "Kazakhstan":
                return  gmt.AddMinutes(360).ToString();
            case "Myanmar":
                return  gmt.AddMinutes(390).ToString();                
            case "Cambodia":
            case "Laos":
                return  gmt.AddMinutes(420).ToString();            
            case "Philippines":
            case "Malaysia":
            case "Hong Kong":
            case "China":
                return  gmt.AddMinutes(480).ToString();               
            case "Japan":
            case "Korea":
                return  gmt.AddMinutes(540).ToString();                
            case "Micronesia":
                return  gmt.AddMinutes(720).ToString();               
            case "Papua New Guinea":
            case "Australia":
                return gmt.AddMinutes(600).ToString();
            case "New Caledonia":
                return gmt.AddMinutes(660).ToString();                
            case "New Zealand":
            case "Fiji":
                return  gmt.AddMinutes(720).ToString();
            case "Argentina":
            case "Brazil":
                return  gmt.AddMinutes(-180).ToString();                
            case "Cuba":
                return gmt.AddMinutes(-300).ToString();                    
            case "Aruba":
            case "Paraguay":
            case "Netherlands Antilles":
            case "Barbados":
            case "Chile":
            case "Dominican Republic":
            case "Guyana":
                return gmt.AddMinutes(-240).ToString();
            case "Bahamas":
                return gmt.AddMinutes(-240).ToString();
            case "Peru":
            case "Panama":
            case "Jamaica":
            case "Haiti":
            case "Colombia":
            case "Canary Islands":
                return gmt.AddMinutes(-300).ToString();
            case "Bhutan":
                return gmt.AddMinutes(360).ToString();
            case "Belize":
            case "Mexico":
            case "Honduras":
            case "Canada":
                return gmt.AddMinutes(-360).ToString();
            case "Nicaragua":
                return gmt.AddMinutes(-300).ToString();

            case "United States Of America":
                return gmt.AddMinutes(-480).ToString();
            case "French Polynesia":
                return gmt.AddMinutes(720).ToString();
            case "Samoa":
                return gmt.AddMinutes(-660).ToString();
            case "Singapore":
                return gmt.AddMinutes(480).ToString();
            case "Slovak Republic":
                return gmt.AddMinutes(60).ToString();          
            case "Solomon Islands":
                return gmt.AddMinutes(660).ToString();              
            case "St Helena":
                return gmt.AddMinutes(0).ToString();
            case "St Kitts & Nevia":
                return gmt.AddMinutes(-240).ToString();
            case "St Lucia":
                return gmt.AddMinutes(-240).ToString();           
            case "Surinam":
                return gmt.AddMinutes(-180).ToString();
            case "Swaziland":
                return gmt.AddMinutes(120).ToString();
            case "Sweden":
                return gmt.AddMinutes(60).ToString();
            case "Switzerland":
                return gmt.AddMinutes(60).ToString();
            case "Syria":
                return gmt.AddMinutes(120).ToString();
            case "Taiwan":
                return gmt.AddMinutes(480).ToString();
            case "Tajikistan":
                return gmt.AddMinutes(300).ToString();
            case "Tanzania":
                return gmt.AddMinutes(180).ToString();
            case "Thailand":
                return gmt.AddMinutes(420).ToString();
            case "Tonga":
                return gmt.AddMinutes(0).ToString();
            case "Trinidad & Tobago":
                return gmt.AddMinutes(-240).ToString();
            case "Tunisia":
                return gmt.AddMinutes(60).ToString();          
            case "Turkmenistan":
                return gmt.AddMinutes(300).ToString();
            case "Turks & Caicos Islands":
                return gmt.AddMinutes(-240).ToString();
            case "Tuvalu":
                return gmt.AddMinutes(720).ToString();
            case "Uganda":
                return gmt.AddMinutes(180).ToString();
            case "Ukraine":
                return gmt.AddMinutes(120).ToString();          
            case "Uruguay":
                return gmt.AddMinutes(-180).ToString();
            case "USA":
                return gmt.AddMinutes(-480).ToString();
            case "Uzbekistan":
                return gmt.AddMinutes(300).ToString();
            case "Vanuatu":
                return gmt.AddMinutes(660).ToString();
            case "Venezuela":
                return gmt.AddMinutes(-240).ToString();
            case "Vietnam":
                return gmt.AddMinutes(420).ToString();
            case "Wallis & Futuna Islands":
                return gmt.AddMinutes(720).ToString();
            case "Yemen":
                return gmt.AddMinutes(180).ToString();
            case "Zambia":
                return gmt.AddMinutes(120).ToString();
            case "Zimbabwe":
                return gmt.AddMinutes(120).ToString();
            default:
                return "";
        }
    }

谢谢

编辑

客户端代码

经过大量搜索后,我得到了解决方案。我可以将用户 pc 时区保存在 cookie 中,并从服务器端访问该 cookie 时区,然后我可以从那里获取用户 pc 日期和时间。但存在一种风险,即用户可能会将他们的时区更改为不同的时区。
$(function(){
    setTimezoneCookie();
});


function setTimezoneCookie(){

    var timezone_cookie = "timezoneoffset";

    // if the timezone cookie not exists create one.
    if (!$.cookie(timezone_cookie)) {

        // check if the browser supports cookie
        var test_cookie = 'test cookie';
        $.cookie(test_cookie, true);

        // browser supports cookie
        if ($.cookie(test_cookie)) {

            // delete the test cookie
            $.cookie(test_cookie, null);

            // create a new cookie
            $.cookie(timezone_cookie, new Date().getTimezoneOffset());

            // re-load the page
            location.reload();
        }
    }
    // if the current timezone and the one stored in cookie are different
    // then store the new timezone in the cookie and refresh the page.
    else {        

        var storedOffset = parseInt($.cookie(timezone_cookie));
        var currentOffset = new Date().getTimezoneOffset();

        // user may have changed the timezone
        if (storedOffset !== currentOffset) {
            $.cookie(timezone_cookie, new Date().getTimezoneOffset());
            location.reload();
        }
    }
}

server side code
--------------------
public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.Request.Cookies.AllKeys.Contains("timezoneoffset"))
        {
            Session["timezoneoffset"] =
                HttpContext.Request.Cookies["timezoneoffset"].Value;
        }
        base.OnActionExecuting(filterContext);
    }
}

public static string ToClientTime(this DateTime dt)
{
    // read the value from session
    var timeOffSet = HttpContext.Current.Session["timezoneoffset"]; 

    if (timeOffSet != null)
    {
        var offset = int.Parse(timeOffSet.ToString());
        dt = dt.AddMinutes(-1 * offset);

        return dt.ToString();
    }

    // if there is no offset in session return the datetime in server timezone
    return dt.ToLocalTime().ToString();
}

完成此任务的另一种方法
function getTimezoneName() {
    tmSummer = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0));
    so = -1 * tmSummer.getTimezoneOffset();
    tmWinter = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0));
    wo = -1 * tmWinter.getTimezoneOffset();

    if (-660 == so && -660 == wo) return 'Pacific/Midway';
    if (-600 == so && -600 == wo) return 'Pacific/Tahiti';
    if (-570 == so && -570 == wo) return 'Pacific/Marquesas';
    if (-540 == so && -600 == wo) return 'America/Adak';
    if (-540 == so && -540 == wo) return 'Pacific/Gambier';
    if (-480 == so && -540 == wo) return 'US/Alaska';
    if (-480 == so && -480 == wo) return 'Pacific/Pitcairn';
    if (-420 == so && -480 == wo) return 'US/Pacific';
    if (-420 == so && -420 == wo) return 'US/Arizona';
    if (-360 == so && -420 == wo) return 'US/Mountain';
    if (-360 == so && -360 == wo) return 'America/Guatemala';
    if (-360 == so && -300 == wo) return 'Pacific/Easter';
    if (-300 == so && -360 == wo) return 'US/Central';
    if (-300 == so && -300 == wo) return 'America/Bogota';
    if (-240 == so && -300 == wo) return 'US/Eastern';
    if (-240 == so && -240 == wo) return 'America/Caracas';
    if (-240 == so && -180 == wo) return 'America/Santiago';
    if (-180 == so && -240 == wo) return 'Canada/Atlantic';
    if (-180 == so && -180 == wo) return 'America/Montevideo';
    if (-180 == so && -120 == wo) return 'America/Sao_Paulo';
    if (-150 == so && -210 == wo) return 'America/St_Johns';
    if (-120 == so && -180 == wo) return 'America/Godthab';
    if (-120 == so && -120 == wo) return 'America/Noronha';
    if (-60 == so && -60 == wo) return 'Atlantic/Cape_Verde';
    if (0 == so && -60 == wo) return 'Atlantic/Azores';
    if (0 == so && 0 == wo) return 'Africa/Casablanca';
    if (60 == so && 0 == wo) return 'Europe/London';
    if (60 == so && 60 == wo) return 'Africa/Algiers';
    if (60 == so && 120 == wo) return 'Africa/Windhoek';
    if (120 == so && 60 == wo) return 'Europe/Amsterdam';
    if (120 == so && 120 == wo) return 'Africa/Harare';
    if (180 == so && 120 == wo) return 'Europe/Athens';
    if (180 == so && 180 == wo) return 'Africa/Nairobi';
    if (240 == so && 180 == wo) return 'Europe/Moscow';
    if (240 == so && 240 == wo) return 'Asia/Dubai';
    if (270 == so && 210 == wo) return 'Asia/Tehran';
    if (270 == so && 270 == wo) return 'Asia/Kabul';
    if (300 == so && 240 == wo) return 'Asia/Baku';
    if (300 == so && 300 == wo) return 'Asia/Karachi';
    if (330 == so && 330 == wo) return 'Asia/Calcutta';
    if (345 == so && 345 == wo) return 'Asia/Katmandu';
    if (360 == so && 300 == wo) return 'Asia/Yekaterinburg';
    if (360 == so && 360 == wo) return 'Asia/Colombo';
    if (390 == so && 390 == wo) return 'Asia/Rangoon';
    if (420 == so && 360 == wo) return 'Asia/Almaty';
    if (420 == so && 420 == wo) return 'Asia/Bangkok';
    if (480 == so && 420 == wo) return 'Asia/Krasnoyarsk';
    if (480 == so && 480 == wo) return 'Australia/Perth';
    if (540 == so && 480 == wo) return 'Asia/Irkutsk';
    if (540 == so && 540 == wo) return 'Asia/Tokyo';
    if (570 == so && 570 == wo) return 'Australia/Darwin';
    if (570 == so && 630 == wo) return 'Australia/Adelaide';
    if (600 == so && 540 == wo) return 'Asia/Yakutsk';
    if (600 == so && 600 == wo) return 'Australia/Brisbane';
    if (600 == so && 660 == wo) return 'Australia/Sydney';
    if (630 == so && 660 == wo) return 'Australia/Lord_Howe';
    if (660 == so && 600 == wo) return 'Asia/Vladivostok';
    if (660 == so && 660 == wo) return 'Pacific/Guadalcanal';
    if (690 == so && 690 == wo) return 'Pacific/Norfolk';
    if (720 == so && 660 == wo) return 'Asia/Magadan';
    if (720 == so && 720 == wo) return 'Pacific/Fiji';
    if (720 == so && 780 == wo) return 'Pacific/Auckland';
    if (765 == so && 825 == wo) return 'Pacific/Chatham';
    if (780 == so && 780 == wo) return 'Pacific/Enderbury'
    if (840 == so && 840 == wo) return 'Pacific/Kiritimati';
    return 'US/Pacific';
}

最佳答案

不要遵循该代码。这是可怕的代码,比我现在有时间研究的方式更多。

基本上,您需要获取用户所在的时区——这可能需要的不仅仅是国家,因为几个国家跨越多个时区。

如果你想坚持“ Vanilla ”.NET,你可以使用 TimeZoneInfo - 您需要知道用户时区的 ID,此时您可以使用:

var zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
var now = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, zone);

另一种选择是使用我的Noda Time库 - 不仅允许您使用 Windows 时区,还可以使用更广泛使用的 IANA/TZDB在我看来,时区......以及总体上提供更好的日期/时间 API。例如,您将使用:
// zoneId is the TZDB ID, e.g. "Europe/London"
DateTimeZone zone = DateTimeZoneProviders.Tzdb[zoneId];
// clock would be an IClock implementation of some description; rather than
// having a static method, an interface encourages testability. 
ZonedDateTime now = clock.Now.InZone(zone);

(请注意,在 Noda Time 2.0 中,IClock 接口(interface)发生了一些变化……上面的代码适用于 Noda Time 1.x。)

在这两种情况下,您都需要格式化 DateTimeZonedDateTime如果您需要一个字符串 - 您使用的格式很可能是用户特定的。在这两种情况下,您还需要计算出用户的时区,这远非简单。在不知道您正在构建什么样的应用程序的情况下,很难就这方面的事情给您建议。

关于c# - 如何从用户 pc TimeZone 中提取当前日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379517/

相关文章:

c# - 动态添加控件不会显示在 asp.net Web 窗体的面板内

c# - WebBrowser 文本选择更改时触发事件

c# - Unity StopCoroutine 不工作

c# - WPF前要不要学Window Form?

C# IndexOutOfRange 数组异常

c# - 在 Visual Studio 中按 NUnit 的类别属性运行/分组测试

c# - 无法将 HttpResponseMessage 反序列化为模型对象

c# - 使用 SWIG,如何将 C++ void func(Class& out) 包装为 C# Class func()?

c# - ServiceController 类未导入 C#

c# - 页面计数器不工作 ASP.NET C#