Advertisement

获取北京标准时间

阅读量:
复制代码
 ///<summary>

    
     /// 获取标准北京时间
    
     ///</summary>
    
     ///<returns></returns>
    
     public static DateTime GetBeijingTime()
    
     {
    
         DateTime dt;
    
         HttpWebRequest wrt = null;
    
         HttpWebResponse wrp = null;
    
         try
    
         {
    
             wrt = (HttpWebRequest)WebRequest.Create("http://www.beijing-time.org/time.asp");
    
             wrt.Method = "POST";
    
             wrt.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
    
             wrt.ContentType = "application/x-www-form-urlencoded";
    
             wrt.ContentLength = 0;
    
             wrt.KeepAlive = false;
    
             wrt.ProtocolVersion = HttpVersion.Version10;
    
             wrp = (HttpWebResponse)wrt.GetResponse();
    
  
    
             string year = wrp.LastModified.Year.ToString();
    
             string month = wrp.LastModified.Month.ToString();
    
             string day = wrp.LastModified.Day.ToString() ;
    
             string hour = wrp.LastModified.Hour.ToString();
    
             string minite = wrp.LastModified.Minute.ToString();
    
             string second = wrp.LastModified.Second.ToString();
    
             string curTime = year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second;
    
             dt = DateTime.Parse(curTime);
    
         }
    
         catch (WebException ex)
    
         {
    
             return DateTime.Parse("2011-1-1");
    
         }
    
         catch (Exception ex)
    
         {
    
             return DateTime.Parse("2011-1-1");
    
         }
    
         finally
    
         {
    
             if (wrp != null)
    
                 wrp.Close();
    
             if (wrt != null)
    
                 wrt.Abort();
    
         }
    
         return dt;
    
     }

最开始是用网上的方法获取,可是一直报错,错误原因:无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接

后来改成httpwebrequest形式,然后返回值直接取出来日期进行组合,用原来的方法会报错,而且感觉很麻烦

参考代码网址:https://www.cnblogs.com/shadowme/p/6250029.html

全部评论 (0)

还没有任何评论哟~