6

how can i get current time From Internet (External Resource - Not From Server)?
Edited
For Example From the Below WebSite :
http://www.timeanddate.com/worldclock
Reason
i will redirect my pages to a Lock page after one month (by checking DateTime.Now) and in that page user should input activation code for comming back...
for some security reasons i want to get the current Date/Time From Out Of My Server...

thanks in advance

SilverLight
  • 19,668
  • 65
  • 192
  • 300

5 Answers5

11

I think this will help you out of it.Apply the below mentioned code for retrieving the date from Internet.

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;
    }
darnir
  • 4,870
  • 4
  • 32
  • 47
palaniappan
  • 173
  • 3
  • @dear palaniappan ... thanks for your nice answer! i think i get my answer (i am testing it)! but for complete your answer , is there any server out there that uses web services ? – SilverLight Jul 13 '11 at 09:23
  • Hi we can use it with out using webservice also – palaniappan Jul 13 '11 at 11:48
  • what the above code will return... if any date time then which country date & time it will return? – Thomas Dec 04 '14 at 20:09
  • You should avoid use IP o DNS because some of them are not available anymore. Read all notes of NIST Internet Time Servers ([NIST link](http://tf.nist.gov/tf-cgi/servers.cgi)). Important Note: The global address time.nist.gov is resolved to all of the server addresses below in a round-robin sequence to equalize the load across all of the servers. Whether you connect to a server using the name or the IP address, it is a bad practice to “hard-code” a particular server name or address into a device so that these parameters cannot be changed by the end user. – UUHHIVS Jun 08 '16 at 16:35
3

You can't, not by using DateTime.Now. It is a property of the DateTime structure that can't be overridden.

You can use an NTP server to get time (though there is not support in the BCL for one).

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • dear @Oded thanks for answer! would u plz explain more! how can i implement it in vs2010 and using it with asp.net and c#? – SilverLight Jul 13 '11 at 09:12
0

You can get the DateTime using JavaScript

    myDate = new Date();
    myday = myDate.getDay();
    mymonth = myDate.getMonth();
    myweekday= myDate.getDate();

Check this article to javascript date and time object

and look at this as well JavaScript Date Object - Dead link fixed

Off The Gold
  • 1,228
  • 15
  • 28
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
  • 1
    This will get the _client_ date time. Of _any_ client, so different clients will not agree with each other. – Oded Jul 13 '11 at 08:37
  • I think He is looking for client DateTime – Muhammad Akhtar Jul 13 '11 at 08:39
  • I think it is very unclear, he isn't stating where the date should be coming from (the Internet???). – Oded Jul 13 '11 at 08:40
  • thanks for comments / but sometimes client datetime is not true and so can not be a good goal for getting datetime ... – SilverLight Jul 13 '11 at 08:46
  • Question is very clear - how can get DateTime From Internet, then why stupid answer given using JavaScript. Also, in comments, he stated that he thought the user was looking for client DateTime. Thats why down voted – Arun Feb 09 '17 at 20:32
0

Why not use a HttpRequest to query the RSS feed of a site which gives world time? Is this what you mean?

Extrakun
  • 19,057
  • 21
  • 82
  • 129
  • dear @Extrakun : by this way how can i get Current DateTime By c# Code - I do n't want to show that to my user / just want to get current time by c# code and using it for reactive locked pages! – SilverLight Jul 13 '11 at 08:59
0

Why would you want to get it from the internet, you would still be getting it from someone's sever.

  • 1
    dear @JohnCoops786 : for some security reasons about my web hosting server i want to read dateTime From Out Of my server ! – SilverLight Jul 13 '11 at 08:47