陋室铭
永远也不要停下学习的脚步(大道至简至易)

复制代码
1 /// <summary>  
2 /// 本地时间转成GMT时间  
3 /// </summary>  
4  public static string ToGMTString(DateTime dt)  
5  {  
6     return dt.ToUniversalTime().ToString("r");  
7 }  
复制代码

string s = ToGMTString(DateTime.Now);
//本地时间为:2016-6-30 10:04:39
//转换后的时间为:Thu, 30 Jun 2016 2:04:39 GMT

复制代码
1 /// <summary>  
2 /// 本地时间转成GMT格式的时间  
3 /// </summary>  
4 public static string ToGMTFormat(DateTime dt)  
5 {  
6     return dt.ToString("r") + dt.ToString("zzz").Replace(":", "");  
7 }
复制代码

string s = ToGMTFormat(DateTime.Now);
//本地时间为:2016-6-30 10:04:39
//转换后的时间为:Thu, 30 Jun 2016 10:04:39 GMT+0800

复制代码
 1 /// <summary>  
 2 /// GMT时间转成本地时间  
 3 /// </summary>  
 4 /// <param name="gmt">字符串形式的GMT时间</param>  
 5 /// <returns></returns>  
 6 public static DateTime GMT2Local(string gmt)  
 7 {  
 8     DateTime dt = DateTime.MinValue;  
 9     try  
10     {  
11         string pattern = "";  
12         if (gmt.IndexOf("+0") != -1)  
13         {  
14             gmt = gmt.Replace("GMT", "");  
15             pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";  
16         }  
17         if (gmt.ToUpper().IndexOf("GMT") != -1)  
18         {  
19             pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";  
20         }  
21         if (pattern != "")  
22         {  
23             dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);  
24             dt = dt.ToLocalTime();  
25         }  
26         else  
27         {  
28             dt = Convert.ToDateTime(gmt);  
29         }  
30     }  
31     catch  
32     {  
33     }  
34     return dt;  
35 }
复制代码

DateTime dt1 = GMT2Local("Thu, 30 Jun 2016 02:04:39 GMT"); 
//转换后的dt1为:2016-6-30 10:04:39
DateTime dt2 = GMT2Local("Thu, 30 Jun 2016 10:04:39 GMT+0800");
//转换后的dt2为:2016-6-30 10:04:39

posted on 2018-10-08 12:03  宏宇  阅读(8347)  评论(0编辑  收藏  举报