如何从互联网获取DateTime? [英] How to get DateTime from the internet?
本文介绍了如何从互联网获取DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用C#从互联网或服务器获取当前日期和时间?我想获得时间如下:
How to get current date and time from internet or server using C#? I am trying to get time as follows:
public static DateTime GetNetworkTime (string ntpServer)
{
IPAddress[] address = Dns.GetHostEntry(ntpServer).AddressList;
if (address == null || address.Length == 0)
throw new ArgumentException("Could not resolve ip address from '" + ntpServer + "'.", "ntpServer");
IPEndPoint ep = new IPEndPoint(address[0], 123);
return GetNetworkTime(ep);
}
我将服务器IP地址传递为 netServer <
I am passing server IP address as netServer
, but it does not work properly.
推荐答案
对于端口13被阻塞的环境,来自NIST的时间可以
For environments where port 13 is blocked, time from NIST can be web scraped as below,
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;
}
这篇关于如何从互联网获取DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文