c#获取网络时间

        public static DateTime GetInternetDate()
        {
            var client = new TcpClient("time.nist.gov", 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);
                return localDateTime;
            }
        }

 

        public static DateTime GetInternetDate1()
        {
            //var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
            var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.baidu.com/");
            var response = myHttpWebRequest.GetResponse();
            string todaysDates = response.Headers["date"];
            DateTime dt = DateTime.ParseExact(todaysDates,
                                       "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
                                       CultureInfo.InvariantCulture.DateTimeFormat,
                                       DateTimeStyles.AssumeUniversal);
            return dt;
        }

posted @ 2017-03-23 14:40  beautifulday  阅读(1156)  评论(0编辑  收藏  举报