免费获取网络时间的类
写了个获取网络时间的类,从三个地方获取,不收费的那种。分享出来供大家参考。
/// <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");
}
}
}