如何从互联网上获取DateTime?

hml*_*snk 44 datetime c#-4.0

如何使用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)

  • 您可以只检索DATE标头,而不是使用正则表达式.if(DateTime.TryParse(response.GetResponseHeader("DATE"),out dateTime))return dateTime; (5认同)
  • 我只是通过检查http响应标题"Date"参数从任何热门网站(比如google)获取互联网时间.这样您就不必依赖任何一项服务,但可以轻松地将其更改为任何其他服务. (4认同)

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)

  • 您应该使用格式字符串:“yy-MM-dd HH:mm:ss”。HH 是 24 小时制。hh 是 12 小时,请参阅:http://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx (2认同)

小智 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)

  • 好的解决方案 适用于`google.com`,`yahoo.com`和`msdn.com`.在msdn.com上有点延迟.此外,我们需要明确地"处理响应对象"或将其包含在使用{...}语句中 (8认同)
  • 很好的解决方案,但HttpWebRequest强制转换是多余的.此外,您可以简化这样的代码:`using(WebResponse response = WebRequest.Create("http://www.microsoft.com").GetResponse())return DateTime.ParseExact(response.Headers ["date"] ,"ddd,dd MMM yyyy HH:mm:ss'GMT'",CultureInfo.InvariantCulture.DateTimeFormat,DateTimeStyles.AssumeUniversal); ` (8认同)
  • 惊人的答案。适合端口被阻塞的人。 (2认同)

小智 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应用程序依赖于提供准确日期信息的服务至关重要.我在我的应用程序中使用了这里建立的代码之一,它确实搞砸了.


dod*_*ian 5

同一想法的另一个版本:

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()来获得当前本地时间。