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);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM