RajithKannanrs Ответов: 6

Получить время из интернета


Есть ли у кого-нибудь код, чтобы получить время из интернета?

Bojjaiah

можете ли вы прояснить свой вопрос?

6 Ответов

Рейтинг:
46

Neha Thanka

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;
    }


[no name]

Этот сценарий длится целую вечность. Я проверил его дважды, и мне потребовалось более 30 секунд, чтобы получить какой-либо ответ.

Этот скрипт работает лучше:
http://stackoverflow.com/a/9830462/4012980

Рейтинг:
39

riteshsingh_jsr

Вы можете проверить это, было бы полезно для вас

http://www.codeproject.com/Answers/140474/how-to-get-internet-time-from-vb-net-application.aspx


Рейтинг:
33

Code 89

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

Попробовать это

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);
}


пожалуйста, пройдите по этой ссылкеhttp://stackoverflow.com/questions/6435099/get-datetime-from-internet-in-c-sharp


Рейтинг:
23

RempoRaaj

обратитесь по адресу:"http://www.codeproject.com/KB/vb/daytime.aspx"


Рейтинг:
1

User 11197367

Это прекрасно работает для меня:

На моем устройстве это занимает около 10 секунд. Но секунды в моем случае не имеют значения, потому что я использую их только для того, чтобы 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;
}

Вся заслуга в том, что http://stackoverflow.com/a/9830462/4012980


Kornfeld Eliyahu Peter

Вам не кажется, что после 3 лет и 4 принятых ответов ОП уже получил его?..

[no name]

Это не может повредить

Kornfeld Eliyahu Peter

Не принято отвечать на такие старые, ответные вопросы снова спустя годы - это пахнет репутационной охотой...
Используйте свои знания, чтобы ответить на новые вопросы...

[no name]

Да, извините, я новый пользователь

Но это нормально, пока данная информация стоит больше, чем ценность репутации.

Wernervantonder

Я прочитал эту статью 4 года спустя и нашел ответ iLembus интересным. Так что бери свою репутацию и сохраняй ее. кого это волнует.

johnmcpherson10

Почему распространение знаний неправильно?
Проверьте свое эго, мне кажется, что вы просто хотите ударить кого-то, кто пытается помочь.
Кто взял твои конфеты?

Рейтинг:
1

Prashant Manjule

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;
}