如何使用C#从互联网或服务器获取当前日期和时间?我想时间如下:
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);
}
Run Code Online (Sandbox Code Playgroud)
我正在传递服务器IP地址netServer,但它无法正常工作.
Nem*_*emo 55
对于端口13被阻止的环境,NIST的时间可以被网页抓取,如下所示,
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;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*Aza 40
以下是可用于从NIST Internet Time Service检索时间的代码示例
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 31
这是一个从标题中获取时间的快速代码,无需端口13即可运行
public static DateTime GetNistTime()
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
var response = myHttpWebRequest.GetResponse();
string todaysDates = response.Headers["date"];
return DateTime.ParseExact(todaysDates,
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
Run Code Online (Sandbox Code Playgroud)
小智 9
事情可能会出错.上面建立的代码的所有实现都容易出错.有时,它有效,有时它会收到WebExpection错误消息.
更好的实施:
try{
using (var response =
WebRequest.Create("http://www.google.com").GetResponse())
//string todaysDates = response.Headers["date"];
return DateTime.ParseExact(response.Headers["date"],
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
catch (WebException)
{
return DateTime.Now; //In case something goes wrong.
}
Run Code Online (Sandbox Code Playgroud)
结论:
让您的Web应用程序依赖于提供准确日期信息的服务至关重要.我在我的应用程序中使用了这里建立的代码之一,它确实搞砸了.
同一想法的另一个版本:
public static class InternetTime
{
public static DateTimeOffset? GetCurrentTime()
{
using (var client = new HttpClient())
{
try
{
var result = client.GetAsync("https://google.com",
HttpCompletionOption.ResponseHeadersRead).Result;
return result.Headers.Date;
}
catch
{
return null;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
HttpCompletionOption.ResponseHeadersRead由于我们只需要HTTP标头,因此此处用于防止加载其余的响应。
使用InternetTime.GetCurrentTime().Value.ToLocalTime()来获得当前本地时间。