Click here to Skip to main content
14,330,512 members
Rate this:
Please Sign up or sign in to vote.
See more:
Does anyone have code to get time from internet?
Posted
Updated 8-Oct-19 23:52pm
Comments
Bojjaiah 15-Dec-11 5:22am
   
can u clarify your question.
Rate this:
Please Sign up or sign in to vote.

Solution 2

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;
    }
   
Comments
iLembus 21-Dec-14 15:27pm
   
That Script takes like Forever. I tested it twice and it took both over 30 secs to get any response.

This Script works better:
http://stackoverflow.com/a/9830462/4012980
Rate this:
Please Sign up or sign in to vote.

Solution 1

You can check out this, would be helpful for u

http://www.codeproject.com/Answers/140474/how-to-get-internet-time-from-vb-net-application.aspx
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

http://www.google.com/codesearch/

Try this
var client = new TcpClient("64.90.182.55", 13);
using (var streamReader = new StreamReader(client.GetStream()))
{
    var response = streamReader.ReadToEnd();
    var utcDateTimeString = response.Substring(7, 17);
    var localDateTime = DateTime.ParseExact(utcDateTimeString, "yy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
}


pls go thru this linkhttp://stackoverflow.com/questions/6435099/get-datetime-from-internet-in-c-sharp
   
Rate this:
Please Sign up or sign in to vote.

Solution 4

refer at:"http://www.codeproject.com/KB/vb/daytime.aspx"
   
Rate this:
Please Sign up or sign in to vote.

Solution 6

This works fine for me:

Takes like 10 secs on my device. But seconds doesnt matter in my case, because i only use it to campare to TimeDate.Now
public static DateTime GetNistTime()
{
    DateTime dateTime = DateTime.MinValue;

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://nist.time.gov/actualtime.cgi?lzbc=siqm9b");
    request.Method = "GET";
    request.Accept = "text/html, application/xhtml+xml, */*";
    request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
    request.ContentType = "application/x-www-form-urlencoded";
    request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); //No caching
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        StreamReader stream = new StreamReader(response.GetResponseStream());
        string html = stream.ReadToEnd();//<timestamp time="\"1395772696469995\"" delay="\"1395772696469995\"/">
        string time = Regex.Match(html, @"(?<=\btime="")[^""]*").Value;
        double milliseconds = Convert.ToInt64(time) / 1000.0;
        dateTime = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToLocalTime();
    }

    return dateTime;
}

All Credit to http://stackoverflow.com/a/9830462/4012980
   
v2
Comments
Kornfeld Eliyahu Peter 21-Dec-14 15:36pm
   
Don't you think that after 3 years and 4 accepted answers OP got it already...
iLembus 21-Dec-14 15:47pm
   
It can't harm
Kornfeld Eliyahu Peter 21-Dec-14 15:56pm
   
It is not accepted to answer such old, answered questions again after years - it has the smell of reputation hunting...
Use your knowledge to answer new questions...
iLembus 21-Dec-14 18:48pm
   
Yea Sorry, I am new User

But it's fine as long as the given Information is worth more than the worth of the Reputition.
Wernervantonder 17-Nov-15 11:27am
   
I read this article 4 years later and found iLembus answer interesting. So take your reputation and keep it. who cares.
johnmcpherson10 8-Mar-18 8:51am
   
Why is the dissemination of knowledge wrong?
Check your ego, It appears to me that you just want to bash someone who is trying to help.
Who took your candy?
Rate this:
Please Sign up or sign in to vote.

Solution 8

public static Nullable<DateTime> GetDateTime()
{
    Nullable<DateTime> dateTime = null;
    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.microsoft.com");
    request.Method = "GET";
    request.Accept = "text/html, application/xhtml+xml, */*";
    request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
    request.ContentType = "application/x-www-form-urlencoded";
    request.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
    try
    {
        System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            string todaysDates = response.Headers["date"];

            dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat, System.Globalization.DateTimeStyles.AssumeUniversal);
        }
    }
    catch
    {
        dateTime = null;
    }
    return dateTime;
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100