[C#] C#同步网络时间的代码 →→→→→进入此内容的聊天室

来自 , 2019-04-27, 写在 C#, 查看 127 次.
URL http://www.code666.cn/view/4ef1477d
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.IO;  
  6. using System.Net;  
  7. using System.Net.Sockets;  
  8. using System.Text.RegularExpressions;  
  9. using System.Runtime.InteropServices;
  10. using System.Runtime;    
  11.  
  12.  
  13.  
  14.     /// <summary>  
  15.     /// 网络时间  
  16.     /// </summary>  
  17.     public class NetTime
  18.     {
  19.        
  20.         /// <summary>  
  21.         /// 获取标准北京时间,读取http://www.beijing-time.org/time.asp  
  22.         /// </summary>  
  23.         /// <returns>返回网络时间</returns>  
  24.         public DateTime GetBeijingTime()
  25.         {
  26.          
  27.             DateTime dt;
  28.             WebRequest wrt = null;
  29.             WebResponse wrp = null;
  30.             try
  31.             {
  32.                 wrt = WebRequest.Create("http://www.beijing-time.org/time.asp");
  33.                 wrp = wrt.GetResponse();
  34.  
  35.                 string html = string.Empty;
  36.                 using (Stream stream = wrp.GetResponseStream())
  37.                 {
  38.                     using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
  39.                     {
  40.                         html = sr.ReadToEnd();
  41.                     }
  42.                 }
  43.  
  44.                 string[] tempArray = html.Split(';');
  45.                 for (int i = 0; i < tempArray.Length; i++)
  46.                 {
  47.                     tempArray[i] = tempArray[i].Replace("\r\n", "");
  48.                 }
  49.  
  50.                 string year = tempArray[1].Split('=')[1];
  51.                 string month = tempArray[2].Split('=')[1];
  52.                 string day = tempArray[3].Split('=')[1];
  53.                 string hour = tempArray[5].Split('=')[1];
  54.                 string minite = tempArray[6].Split('=')[1];
  55.                 string second = tempArray[7].Split('=')[1];
  56.  
  57.                 dt = DateTime.Parse(year + "-" + month + "-" + day + " " + hour + ":" + minite + ":" + second);
  58.             }
  59.             catch (WebException)
  60.             {
  61.                 return DateTime.Parse("2011-1-1");
  62.             }
  63.             catch (Exception)
  64.             {
  65.                 return DateTime.Parse("2011-1-1");
  66.             }
  67.             finally
  68.             {
  69.                 if (wrp != null)
  70.                     wrp.Close();
  71.                 if (wrt != null)
  72.                     wrt.Abort();
  73.             }
  74.             return dt;
  75.  
  76.         }
  77.     }
  78.  
  79.  
  80. //csharp/6457

回复 "C#同步网络时间的代码"

这儿你可以回复上面这条便签

captcha