免费获取网络时间的类

免费获取网络时间的类

写了个获取网络时间的类,从三个地方获取,不收费的那种。分享出来供大家参考。

        /// <summary>
        /// 从网络获取当前网络时间。
        /// </summary>
        public static DateTime GetNetTime
        {
            get
            {
                GC.Collect();

                System.Net.WebRequest request = null;
                System.Net.WebResponse response = null;
                System.Net.WebHeaderCollection headerCollection = null;
                string content = "";
                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                //Stream newStream = null;
                StreamReader reader = null;
                string datetime = string.Empty;
                bool tryok = false; int trytimes = 0;

                //从淘宝获取
                tryok = false; trytimes = 0;
                while (tryok == false && trytimes < 10)
                {
                    try
                    {
                        trytimes++;
                        //{"api":"mtop.common.getTimestamp","v":"*","ret":["SUCCESS::接口调用成功"],"data":{"t":"1601450788926"}}
                        request = System.Net.WebRequest.Create("http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
                        request.Timeout = 3000;
                        request.Method = "GET";
                        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                        response = request.GetResponse();
                        reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                        content = reader.ReadToEnd();//system.net.webexception:操作已超时      
                        tryok = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("获取网络时间出错:\r\n" + ex.ToString());
                        System.Threading.Thread.Sleep(200);
                    }
                    finally
                    {
                        if (request != null)
                        { request.Abort(); }
                        if (response != null)
                        { response.Close(); }
                        if (headerCollection != null)
                        { headerCollection.Clear(); }
                    }
                }
                if (tryok)
                {
                    //{"api":"mtop.common.getTimestamp","v":"*","ret":["SUCCESS::接口调用成功"],"data":{"t":"1601450788926"}}
                    string dt = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(content)["data"].ToString();
                    string t = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(dt)["t"].ToString();
                    DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));//北京所在东八区
                    return startTime.AddMilliseconds(Str2Int64(t)).ToLocalTime();
                }

                //从淘宝获取
                tryok = false; trytimes = 0;
                while (tryok == false && trytimes < 10)
                {
                    try
                    {
                        trytimes++;
                        //{"sysTime2":"2020-09-30 15:31:06","sysTime1":"20200930153106"}
                        request = System.Net.WebRequest.Create("http://quan.suning.com/getSysTime.do");
                        request.Timeout = 3000;
                        request.Method = "GET";
                        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                        response = request.GetResponse();
                        reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                        content = reader.ReadToEnd();//system.net.webexception:操作已超时      
                        tryok = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("获取网络时间出错:\r\n" + ex.ToString());
                        System.Threading.Thread.Sleep(200);
                    }
                    finally
                    {
                        if (request != null)
                        { request.Abort(); }
                        if (response != null)
                        { response.Close(); }
                        if (headerCollection != null)
                        { headerCollection.Clear(); }
                    }
                }
                if (tryok)
                {
                    //{"sysTime2":"2020-09-30 15:31:06","sysTime1":"20200930153106"}
                    string t = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(content)["sysTime2"].ToString();
                    //DateTime startTime = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));//北京所在东八区
                    //return startTime.AddMilliseconds(Str2Int64(t)).ToLocalTime();
                    return Convert.ToDateTime(t);
                }

                //从百度获取
                tryok = false; trytimes = 0;
                while (tryok == false && trytimes < 10)
                {
                    try
                    {
                        trytimes++;
                        request = System.Net.WebRequest.Create("https://www.baidu.com");
                        request.Timeout = 3000;
                        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                        response = request.GetResponse();
                        headerCollection = response.Headers;
                        foreach (var h in headerCollection.AllKeys)
                        {
                            if (h == "Date")
                            {
                                datetime = headerCollection[h];
                                break;
                            }
                        }
                        tryok = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("获取网络时间出错:\r\n" + ex.ToString());
                        System.Threading.Thread.Sleep(200);
                    }
                    finally
                    {
                        if (request != null)
                        { request.Abort(); }
                        if (response != null)
                        { response.Close(); }
                        if (headerCollection != null)
                        { headerCollection.Clear(); }
                    }
                }
                if (tryok)
                {
                    return Convert.ToDateTime(datetime);
                }
                else
                {
                    return Convert.ToDateTime("1970/1/1 00:00:01");
                }
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值