/// <summary> /// 本地时间转成GMT时间 /// </summary> public static string ToGMTString(DateTime dt) { return dt.ToUniversalTime().ToString("r"); }
string s = ToGMTString(DateTime.Now);
//本地时间为:2011-9-29 15:04:39
//转换后的时间为:Thu, 29 Sep 2011 07:04:39 GMT
/// <summary> /// 本地时间转成GMT格式的时间 /// </summary> public static string ToGMTFormat(DateTime dt) { return dt.ToString("r") + dt.ToString("zzz").Replace(":", ""); }
string s = ToGMTFormat(DateTime.Now);
//本地时间为:2011-9-29 15:04:39
//转换后的时间为:Thu, 29 Sep 2011 15:04:39 GMT+0800
/// <summary> /// GMT时间转成本地时间 /// </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; }
DateTime dt1 = GMT2Local("Thu, 29 Sep 2011 07:04:39 GMT");
//转换后的dt1为:2011-9-29 15:04:39
DateTime dt2 = GMT2Local("Thu, 29 Sep 2011 15:04:39 GMT+0800");
//转换后的dt2为:2011-9-29 15:04:39
分类: C#