c# 獲得網路時間(GMT格式)並轉化為本地時間的方法
阿新 • • 發佈:2019-01-31
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Windows.Forms; //獲得當前網路時間並轉化成本地時間,用法: DateTime netTime = GetNetTime.GMT2Local(GetNetTime.GetNetDate()) namespace NetTime { public class GetNetTime { /// <summary> /// 本地時間轉成GMT時間 /// string s = ToGMTString(DateTime.Now); /// 本地時間為:2014-9-29 15:04:39 /// 轉換後的時間為:Thu, 29 Sep 2014 07:04:39 GMT /// </summary> public static string ToGMTString(DateTime dt) { return dt.ToUniversalTime().ToString("r"); } /// <summary> /// 本地時間轉成GMT格式的時間 /// string s = ToGMTFormat(DateTime.Now); /// 本地時間為:2014-9-29 15:04:39 /// 轉換後的時間為:Thu, 29 Sep 2014 15:04:39 GMT+0800 /// </summary> public static string ToGMTFormat(DateTime dt) { return dt.ToString("r") + dt.ToString("zzz").Replace(":", ""); } /// <summary> /// GMT時間轉成本地時間 /// DateTime dt1 = GMT2Local("Thu, 29 Sep 2014 07:04:39 GMT"); /// 轉換後的dt1為:2014-9-29 15:04:39 /// DateTime dt2 = GMT2Local("Thu, 29 Sep 2014 15:04:39 GMT+0800"); /// 轉換後的dt2為:2014-9-29 15:04:39 /// </summary> /// <param name="gmt">字串形式的GMT時間</param> /// <returns></returns> public static DateTime GMT2Local(string gmt) { DateTime dt = DateTime.MinValue; try { string pattern = ""; if (gmt.IndexOf("+0") != -1) { gmt = gmt.Replace("GMT", ""); pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz"; } if (gmt.ToUpper().IndexOf("GMT") != -1) { pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; } if (pattern != "") { dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); dt = dt.ToLocalTime(); } else { dt = Convert.ToDateTime(gmt); } } catch { } return dt; } /// <summary> /// 獲取國家授時中心網提供的時間。(授時中心連線經常出狀況,暫時用百度網代替) /// 通過分析網頁報頭,查詢Date對應的值,獲得GMT格式的時間。可通過GMT2Local(string gmt)方法轉化為本地時間格式。 /// 用法 DateTime netTime = GetNetTime.GMT2Local(GetNetTime.GetNetDate()); /// </summary> /// <returns></returns> public static string GetNetDate() { try { //WebRequest request = WebRequest.Create("http://www.time.ac.cn");//國家授時中心經常連線不上 WebRequest request = WebRequest.Create("http://www.baidu.com"); request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); WebHeaderCollection myWebHeaderCollection = response.Headers; for (int i = 0; i < myWebHeaderCollection.Count; i++) { string header = myWebHeaderCollection.GetKey(i); string[] values = myWebHeaderCollection.GetValues(header); if (header.Length <= 0 || header == null) { return null; } else if (header == "Date") { return values[0]; } } return null; } catch (Exception ex) { throw ex; } } } }