博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络时间获取
阅读量:5240 次
发布时间:2019-06-14

本文共 2645 字,大约阅读时间需要 8 分钟。

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 }

 

转载于:https://www.cnblogs.com/gdf456/p/9495022.html

你可能感兴趣的文章