0

I heard that if I use nodatime library then I can get date & time based on timezone id. first I change my pc date and time. set to old date and time in my pc and then run the below code which disappoint me.

using NodaTime;

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

Below code display wrong date & time because I set my pc date & time to few days back.

Is there any way that if date & time is wrong but still code display right date & time without depending on user pc date & time setting using Noda Time library. Looking for suggestion.

UPDATE

i follow this way but not sure am i on right tract to achieve my goal.

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();
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • 2
    Brace yourself. Jon Skeet coming.. – Soner Gönül Dec 04 '14 at 19:35
  • is there any wrong in my code because i never use nodatime library before. looking for advise. – Thomas Dec 04 '14 at 19:38
  • 2
    I don't believe nodatime is anything but a library for doing date calculations (very complicated and thorough ones, admittedly). To the best of my knowledge it doesn't do network time lookups and relies on your computer clock being correct. I'm sure the documentation will make this clear though. – Chris Dec 04 '14 at 19:44

1 Answers1

1

If you can't trust the computer's clock, then you must get the time from another source, such as from a network server via NTP connection. Noda Time does not have this functionality.

You may be interested in this answer which describes how to query an NTP server in C#. Note that at the very end of the code in that answer it calls ToLocalTime. Instead, you would use Noda Time's Instant.FromDateTimeUtc method.

Community
  • 1
  • 1
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • I saw the link u gave but do not understand on what basis date time will be return? The function which return date not taking any argument like Timezone id or country code etc.i want to get correct datetime from ntp server based on timezone id but do not want to depend on user pc date time settings. Please give me best advise to achieve my goal. Thanks – Thomas Dec 05 '14 at 05:48
  • Use NTP to get the current UTC time from a trusted server. Then use NodaTime to convert from UTC to the time zone you want. – Matt Johnson-Pint Dec 05 '14 at 16:56
  • please see my update and tell me am i on right track to reach my goal....if not then suggest me where i made the mistake in code and what to do. if possible edit my code. thanks – Thomas Dec 06 '14 at 17:27
  • I had not seen that you are asking the same thing as being asked [here](http://stackoverflow.com/q/27315734). Please limit your questions to that thread. I will respond over there. – Matt Johnson-Pint Dec 07 '14 at 18:12