C# 获取网络时间

网上时间接口很多,但是源码里根本看不到常规的DateTime类型的时间。全是时间戳形式的时间。

这里提供一个接口:

 

http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=1

 

 

 

 

 

取时间戳的前10位,转化成DateTime类型就可以了。前10位精确到秒。

 

        public DateTime GetNowTime()
        {
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                URL = "http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=2",
                Method = "GET",
            };
            HttpResult R = http.GetHtml(item);
            Regex regex = new Regex(@"0=(?<timestamp>\d{10})\d+");
            Match match = regex.Match(R.Html);
            if (match.Success)
            {
              return  GetTime(match.Groups["timestamp"].Value);
            }
            return DateTime.Now;
        }

        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        private DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

 

posted @ 2014-11-23 21:36  来了啊老弟  阅读(14378)  评论(1编辑  收藏  举报