想要根据时区ID Nodatime显示日期和时间

时间:2014-12-04 19:30:46

标签: c# datetime nodatime

我听说如果我使用nodatime库那么我可以获得日期&时间基于时区id。 首先我改变我的电脑日期和时间。设置为我的电脑中的旧日期和时间,然后运行以下代码让我失望。

using NodaTime;

var zoneId = "Asia/Kolkata";
DateTimeZone _zone = DateTimeZoneProviders.Tzdb[zoneId];
ZonedDateTime _now = SystemClock.Instance.Now.InZone(_zone);
var xx = _now.LocalDateTime;

下面的代码显示错误的日期&时间,因为我设置了我的电脑日期&几天前的时间。

有没有办法,如果日期&时间错了,但仍然代码显示正确的日期&时间不依赖于用户的电脑日期&使用Noda Time库设置时间。寻找建议。

更新

我遵循这种方式,但不确定我是否正确地实现了我的目标。

public static DateTime GetFastestNISTDate()
{
        var result = DateTime.MinValue;
    DateTime utcDateTime= 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 utcDateTime;
                            // 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();

1 个答案:

答案 0 :(得分:1)

如果您不能信任计算机的时钟,那么您必须从其他来源获取时间,例如通过NTP连接从网络服务器获取。 Noda Time没有此功能。

您可能对this answer感兴趣,其中介绍了如何在C#中查询NTP服务器。请注意,在该答案的代码的最后,它调用ToLocalTime。相反,您将使用Noda Time的Instant.FromDateTimeUtc方法。