1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms;10 using System.Net;11 12 namespace 时间13 {14 public partial class Form1 : Form15 {16 public Form1()17 {18 InitializeComponent();19 }20 21 private void Form1_Load(object sender, EventArgs e)22 {23 timer1.Interval = 1000;24 timer1.Start();25 }26 private void rftime()27 {28 DateTime dt = DateTime.Now;29 String date = dt.ToLongDateString();30 String time = dt.ToLongTimeString();31 32 33 }34 35 private void timer1_Tick(object sender, EventArgs e)36 {37 { //显示时间38 string netTime = GetNetDateTime();39 if (netTime != "")40 {41 LabNow.Text = "北京时间(网络):" + Convert.ToDateTime(netTime).ToString("yyyy年MM月dd dddd HH时mm分ss秒");42 }43 else44 {45 LabNow.Text = "北京时间(本地):" + DateTime.Now.ToString("yyyy年MM月dd dddd HH时mm分ss秒");46 }47 48 49 }50 }51 public static string GetNetDateTime()52 { //获取网络时间53 WebRequest request = null;54 WebResponse response = null;55 WebHeaderCollection headerCollection = null;56 string datetime = string.Empty;57 try58 {59 request = WebRequest.Create("https://www.baidu.com");60 request.Timeout = 3000;61 request.Credentials = CredentialCache.DefaultCredentials;62 response = request.GetResponse();63 headerCollection = response.Headers;64 foreach (var h in headerCollection.AllKeys)65 {66 if (h == "Date")67 {68 datetime = headerCollection[h];69 }70 }71 return datetime;72 }73 catch (Exception) { return datetime; }74 finally75 {76 if (request != null)77 { request.Abort(); }78 if (response != null)79 { response.Close(); }80 if (headerCollection != null)81 { headerCollection.Clear(); }82 }83 }84 }85 }