C#获取网络时间(初学者)

来源:互联网 发布:简易版支付系统源码 编辑:程序博客网 时间:2024/05/16 12:20

       众所周知,许多游戏有每日登陆奖励,这里涉及到了时间,在联网的的情况下优先获取网络时间,在不联网的情况下只能获取本地时间了,但是本地时间可能容易会被修改,这是弊端。这里学习尝试获取网络时间。

获取网络时间一般会遇到时间戳的概念,时间戳:通俗的说是一串记录某一时刻的数字序列,这串数字是格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总毫秒数。

获取网络时间,首先需要一些网站或者服务器上的标准时间,比如北京时间,百度,中国科学院国家授时中心;这里笔者为了获取方便用的是http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=1


从图上可以看出,直接取第三个到最后一个即可获得时间戳,而不需要像其他网页只有抠出网页源码中的时间那么麻烦。

C#获取网络时间:

        WWW www = new WWW("http://www.hko.gov.hk/cgi-bin/gts/time5a.pr?a=1");        yield return www;        if (www.text != null)        {            string TimeString = www.text;            string time = TimeString.Substring(2);//截取从第三个到最后一个            System.DateTime dtStart = System.TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));            long lTime = long.Parse(time);            System.TimeSpan toNow = new System.TimeSpan(lTime);            System.DateTime timeNow_FromNet = dtStart.Add(toNow);
获取本地时间就更简单了:

System.DateTime timeNow_FromLocal = System.DateTime.Now;
初学者有错误的地方还请多指教,相互交流共同进步!


1 0