c# 获得网络时间(GMT格式)并转化为本地时间的方法

本文介绍了一种使用C#实现的网络时间同步方法,包括将本地时间转换为GMT时间及反之的操作。此外,还提供了从特定网站抓取时间并转换为本地时间的示例。
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;
            }
        }    
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值