【问题标题】:How to get country wise / timezone wise date & time from internet server如何从互联网服务器获取国家/时区明智的日期和时间
【发布时间】:2014-12-05 09:28:50
【问题描述】:

我必须根据用户时区 ID 向用户显示日期和时间。我不能依赖用户电脑日期时间和设置。我在谷歌搜索方式并得到了下面的代码。代码似乎会查询许多外部服务器的日期和时间,但我不清楚我可以从下面的代码中得到什么样的日期和时间。

有些时候我需要印度时间。有时我需要伦敦时间,有时我需要其他国家的当地时间。很少有县有很多时区,这就是为什么我要发送时区 ID/名称并希望根据时区 ID/名称获取日期时间。

所以请指导我如何自定义以下代码,我可以在其中发送用户方的时区 ID,即使用户 pc 日期时间设置错误,例程也会根据时区 ID 返回正确的本地时间。寻找好的帮助。谢谢

public static DateTime GetFastestNISTDate()
{
    var result = DateTime.MinValue;

    // Initialize the list of NIST time servers
    // http://tf.nist.gov/tf-cgi/servers.cgi
    string[] servers = new string[] {
        "nist1-ny.ustiming.org",
        "nist1-nj.ustiming.org",
        "nist1-pa.ustiming.org",
        "time-a.nist.gov",
        "time-b.nist.gov",
        "nist1.aol-va.symmetricom.com",
        "nist1.columbiacountyga.gov",
        "nist1-chi.ustiming.org",
        "nist.expertsmi.com",
        "nist.netservicesgroup.com"
};

        // Try 5 servers in random order to spread the load
        Random rnd = new Random();
        foreach (string server in servers.OrderBy(s => rnd.NextDouble()).Take(5))
        {
            try
            {
                // Connect to the server (at port 13) and get the response
                string serverResponse = string.Empty;
                using (var reader = new StreamReader(new System.Net.Sockets.TcpClient(server, 13).GetStream()))
                {
                    serverResponse = reader.ReadToEnd();
                }

                // If a response was received
                if (!string.IsNullOrEmpty(serverResponse))
                {
                    // Split the response string ("55596 11-02-14 13:54:11 00 0 0 478.1 UTC(NIST) *")
                    string[] tokens = serverResponse.Split(' ');

                    // Check the number of tokens
                    if (tokens.Length >= 6)
                    {
                        // Check the health status
                        string health = tokens[5];
                        if (health == "0")
                        {
                            // Get date and time parts from the server response
                            string[] dateParts = tokens[1].Split('-');
                            string[] timeParts = tokens[2].Split(':');

                            // Create a DateTime instance
                            DateTime utcDateTime = new DateTime(
                                Convert.ToInt32(dateParts[0]) + 2000,
                                Convert.ToInt32(dateParts[1]), Convert.ToInt32(dateParts[2]),
                                Convert.ToInt32(timeParts[0]), Convert.ToInt32(timeParts[1]),
                                Convert.ToInt32(timeParts[2]));

                            // Convert received (UTC) DateTime value to the local timezone
                            result = utcDateTime.ToLocalTime();

                            return result;
                            // Response successfully received; exit the loop

                        }
                    }

                }

            }
            catch
            {
                // Ignore exception and try the next server
            }
        }
        return result;
    }

编辑

    var wc = GetFastestNISTDate();

    var pattern = InstantPattern.CreateWithInvariantCulture("dd/MM/yyyy HH:mm:ss");
    var parseResult = pattern.Parse(wc.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture));
    if (!parseResult.Success)
        throw new InvalidDataException("...whatever...");
    var instant = parseResult.Value;

    var timeZone = DateTimeZoneProviders.Tzdb["Europe/London"];
    var zonedDateTime = instant.InZone(timeZone);
    var bclDateTime = zonedDateTime.ToDateTimeUnspecified();

时区转换不起作用。我从这个函数GetFastestNISTDate(); 得到了正确的日期,接下来我尝试根据我的第一个 UTC 时间获取不同时区的本地日期和时间,但代码返回伦敦的错误时间。我想我弄错了代码。任何人都可以看到并提供帮助。谢谢

【问题讨论】:

  • 请注意TimeZoneInfo 类,可能会节省您的网络通话时间。

标签: c# datetime


【解决方案1】:
DateTime tzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, TimeZone);

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    时间服务器将报告 UTC 时间(这就是变量命名为 utcDateTime 的原因)。

    result = utcDateTime.ToLocalTime(); 行根据您的计算机所在的时区将该 UTC 时间从时间服务器转换为本地时间。如果您想要不同的时区,则需要更改该行。

    正如阿米特所说,您可以使用TimeZoneInfo.ConvertTimeFromUtc 转换到某个指定的时区。请参阅该页面上的示例。

    TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
    DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
    

    【讨论】:

    • 感谢回复。我正在使用 NodaTime 库,它需要像“亚洲/加尔各答”、“欧洲/伦敦”这样的 zoneid。告诉我我可以使用 Nodatime 库和上面的代码。
    • 我的主要座右铭是,即使用户更改了日期和时间,我也应该得到正确的日期和时间。
    • @Mou 是的,你可以使用 NodaTime 来做时区转换。
    • 我看到例程给出了正确的时间 GetFastestNISTDate() 但不明白它获取日期时间的依据是什么。我没有发送任何时区信息或国家代码。那么上述例程如何给出正确的时间。请指导我。谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多