码迷,mamicode.com
首页 > Windows程序 > 详细

C# 获取网络时间

时间:2014-11-23 22:49:53      阅读:380      评论:0      收藏:0      [点我收藏+]

标签:blog   http   ar   os   sp   on   div   2014   art   

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

这里提供两个接口:

 

http://shijian.duoshitong.com/time.php

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

 

这两个接口返回的全是时间戳。都能在源码里找到。。。

bubuko.com,布布扣

 

bubuko.com,布布扣

 

 

 

取时间戳的前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);
        }

 

C# 获取网络时间

标签:blog   http   ar   os   sp   on   div   2014   art   

原文地址:http://www.cnblogs.com/cyberarmy/p/4117497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!