如何从Internet获取当前时间?

时间:2017-05-12 07:12:12

标签: asp.net

如何使用C#从Internet获取当前时间到TextBox

我尝试使用以下代码:

DateTime d = DateTime.UtcNow; 
DateTimeOffset dto2 = DateTimeOffset.UtcNow;

但它只返回正确的日期。

1 个答案:

答案 0 :(得分:0)

对于端口13被阻止的环境,NIST的时间可以通过Web抓取,如下所示

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