#region 获取网络时间
///<summary>
/// 获取中国国家授时中心网络服务器时间发布的当前时间
///</summary>
///<returns></returns>
publicstatic DateTime GetChineseDateTime()
{
DateTime res = DateTime.MinValue;
try
{
string url = "http://www.time.ac.cn/stime.asp";
HttpHelper helper = new HttpHelper();
helper.Encoding = Encoding.Default;
string html = helper.GetHtml(url);
string patDt = @"\d{4}年\d{1,2}月\d{1,2}日";
string patHr = @"hrs\s+=\s+\d{1,2}";
string patMn = @"min\s+=\s+\d{1,2}";
string patSc = @"sec\s+=\s+\d{1,2}";
Regex regDt = new Regex(patDt);
Regex regHr = new Regex(patHr);
Regex regMn = new Regex(patMn);
Regex regSc = new Regex(patSc); res = DateTime.Parse(regDt.Match(html).Value);
int hr = GetInt(regHr.Match(html).Value, false);
int mn = GetInt(regMn.Match(html).Value, false);
int sc = GetInt(regSc.Match(html).Value, false);
res = res.AddHours(hr).AddMinutes(mn).AddSeconds(sc);
}
catch { }
return res;
} ///<summary>
/// 从指定的字符串中获取整数
///</summary>
///<param name="origin">原始的字符串</param>
///<param name="fullMatch">是否完全匹配,若为false,则返回字符串中的第一个整数数字</param>
///<returns>整数数字</returns>
privatestaticint GetInt(string origin, bool fullMatch)
{
if (string.IsNullOrEmpty(origin))
{
return0;
}
origin = origin.Trim();
if (!fullMatch)
{
string pat = @"-?\d+";
Regex reg = new Regex(pat);
origin = reg.Match(origin.Trim()).Value;
}
int res = ;
int.TryParse(origin, out res);
return res;
}
#endregion
///<summary>
/// 获取标准北京时间1
///</summary>
///<returns></returns>
publicstatic DateTime GetStandardTime()
{
//<?xml version="1.0" encoding="GB2312" ?>
//- <ntsc>
//- <time>
// <year>2011</year>
// <month>7</month>
// <day>10</day>
// <Weekday />
// <hour>19</hour>
// <minite>45</minite>
// <second>37</second>
// <Millisecond />
// </time>
// </ntsc>
DateTime dt;
WebRequest wrt = null;
WebResponse wrp = null;
try
{
wrt = WebRequest.Create("http://www.time.ac.cn/timeflash.asp?user=flash");
wrt.Credentials = CredentialCache.DefaultCredentials; wrp = wrt.GetResponse();
StreamReader sr = new StreamReader(wrp.GetResponseStream(), Encoding.UTF8);
string html = sr.ReadToEnd(); sr.Close();
wrp.Close(); int yearIndex = html.IndexOf("<year>") + ;
int monthIndex = html.IndexOf("<month>") + ;
int dayIndex = html.IndexOf("<day>") + ;
int hourIndex = html.IndexOf("<hour>") + ;
int miniteIndex = html.IndexOf("<minite>") + ;
int secondIndex = html.IndexOf("<second>") + ; string year = html.Substring(yearIndex, html.IndexOf("</year>") - yearIndex);
string month = html.Substring(monthIndex, html.IndexOf("</month>") - monthIndex); ;
string day = html.Substring(dayIndex, html.IndexOf("</day>") - dayIndex);
string hour = html.Substring(hourIndex, html.IndexOf("</hour>") - hourIndex);
string minite = html.Substring(miniteIndex, html.IndexOf("</minite>") - miniteIndex);
string second = html.Substring(secondIndex, html.IndexOf("</second>") - secondIndex);
dt = DateTime.Parse(year + "-" + month + "-" + day + "" + hour + ":" + minite + ":" + second);
}
catch (WebException)
{
return DateTime.Parse("2011-1-1");
}
catch (Exception)
{
return DateTime.Parse("2011-1-1");
}
finally
{
if (wrp != null)
wrp.Close();
if (wrt != null)
wrt.Abort();
}
return dt;
} ///<summary>
/// 获取标准北京时间2
///</summary>
///<returns></returns>
publicstatic DateTime GetBeijingTime()
{
//t0 = new Date().getTime();
//nyear = 2011;
//nmonth = 7;
//nday = 5;
//nwday = 2;
//nhrs = 17;
//nmin = 12;
//nsec = 12;
DateTime dt;
WebRequest wrt = null;
WebResponse wrp = null;
try
{
wrt = WebRequest.Create("http://www.beijing-time.org/time.asp");
wrp = wrt.GetResponse(); string html = string.Empty;
using (Stream stream = wrp.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
{
html = sr.ReadToEnd();
}
} string[] tempArray = html.Split(';');
for (int i = ; i < tempArray.Length; i++)
{
tempArray[i] = tempArray[i].Replace("\r\n", "");
} string year = tempArray[].Substring(tempArray[].IndexOf("nyear=") + );
string month = tempArray[].Substring(tempArray[].IndexOf("nmonth=") + );
string day = tempArray[].Substring(tempArray[].IndexOf("nday=") + );
string hour = tempArray[].Substring(tempArray[].IndexOf("nhrs=") + );
string minite = tempArray[].Substring(tempArray[].IndexOf("nmin=") + );
string second = tempArray[].Substring(tempArray[].IndexOf("nsec=") + );
dt = DateTime.Parse(year + "-" + month + "-" + day + "" + hour + ":" + minite + ":" + second);
}
catch (WebException)
{
return DateTime.Parse("2011-1-1");
}
catch (Exception)
{
return DateTime.Parse("2011-1-1");
}
finally
{
if (wrp != null)
wrp.Close();
if (wrt != null)
wrt.Abort();
}
return dt;
}
/// <summary>
/// 获取标准北京时间
/// </summary>
/// <returns></returns>
public static DateTime DataStandardTime()
{
DateTime dt; //返回国际标准时间
//只使用的时间服务器的IP地址,未使用域名
try
{
string[,] 时间服务器 = new string[, ];
int[] 搜索顺序 = new int[] { , , , , , , , , , , , , };
时间服务器[, ] = "time-a.nist.gov";
时间服务器[, ] = "129.6.15.28";
时间服务器[, ] = "time-b.nist.gov";
时间服务器[, ] = "129.6.15.29";
时间服务器[, ] = "time-a.timefreq.bldrdoc.gov";
时间服务器[, ] = "132.163.4.101";
时间服务器[, ] = "time-b.timefreq.bldrdoc.gov";
时间服务器[, ] = "132.163.4.102";
时间服务器[, ] = "time-c.timefreq.bldrdoc.gov";
时间服务器[, ] = "132.163.4.103";
时间服务器[, ] = "utcnist.colorado.edu";
时间服务器[, ] = "128.138.140.44";
时间服务器[, ] = "time.nist.gov";
时间服务器[, ] = "192.43.244.18";
时间服务器[, ] = "time-nw.nist.gov";
时间服务器[, ] = "131.107.1.10";
时间服务器[, ] = "nist1.symmetricom.com";
时间服务器[, ] = "69.25.96.13";
时间服务器[, ] = "nist1-dc.glassey.com";
时间服务器[, ] = "216.200.93.8";
时间服务器[, ] = "nist1-ny.glassey.com";
时间服务器[, ] = "208.184.49.9";
时间服务器[, ] = "nist1-sj.glassey.com";
时间服务器[, ] = "207.126.98.204";
时间服务器[, ] = "nist1.aol-ca.truetime.com";
时间服务器[, ] = "207.200.81.113";
时间服务器[, ] = "nist1.aol-va.truetime.com";
时间服务器[, ] = "64.236.96.53";
int portNum = ;
string hostName;
byte[] bytes = new byte[];
int bytesRead = ;
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
for (int i = ; i < ; i++)
{
hostName = 时间服务器[搜索顺序[i], ];
try
{
client.Connect(hostName, portNum);
System.Net.Sockets.NetworkStream ns = client.GetStream();
bytesRead = ns.Read(bytes, , bytes.Length);
client.Close();
break;
}
catch (System.Exception)
{
}
}
char[] sp = new char[];
sp[] = ' ';
dt = new DateTime();
string str1;
str1 = System.Text.Encoding.ASCII.GetString(bytes, , bytesRead); string[] s;
s = str1.Split(sp);
if (s.Length >= )
{
dt = System.DateTime.Parse(s[] + " " + s[]);//得到标准时间
dt = dt.AddHours();//得到北京时间*/
}
else
{
dt = DateTime.Parse("2011-1-1");
}
}
catch (Exception)
{
dt = DateTime.Parse("2011-1-1");
}
return dt;
}

调用示例:

DateTime dt = Common.GetBeijingTime();// Common.GetStandardTime();
if (dt.ToString() == "2011-1-1 0:00:00")
{
MessageBox.Show("网络异常,不能启动本程序!");
Application.Exit();
return;
}

C#获取获取北京时间多种方法的更多相关文章

  1. 【机房收费系统 4】:VB获取标准北京时间,免除时间误差

    导读:这又是师傅给我指出的一个问题,说实话,其实开始根本没有当回事,觉得麻烦,可是,等我完成了获取标准北京时间后,我发现,这一步,是必须的.谢谢师傅对我的严格要求,让我一步一步的成长起来! 一.事件缘 ...

  2. java中获取日期和时间的方法总结

    1.获取当前时间,和某个时间进行比较.此时主要拿long型的时间值. 方法如下:  要使用 java.util.Date .获取当前时间的代码如下 Date date = new Date(); da ...

  3. PHP获取当前日期和时间的方法

    PHP获取当前日期和时间的方法 来源:wikiHow   时间:2014-12-04 14:49:45   阅读数:7240 分享到:0 [导读] PHP是用来创建网络中动态内容的常见语言,因此PHP ...

  4. WPF 获取系统 DPI 的多种方法

    原文:WPF 获取系统 DPI 的多种方法 WPF 获取系统 DPI 的多种方法 由于 WPF 的尺寸单位和系统的 DPI 相关,我们有时需要获取 DPI 值来进行一些界面布局的调整,本文汇总了一些 ...

  5. cocos2d-x在win32和iOS、android下获取当前系统时间的方法

    最近在游戏里要显示当前系统时间的功能,网上一搜很多写着获取的方法,大都是如下 struct cc_timeval now; CCTime::gettimeofdayCocos2d(&now, ...

  6. JavaScript中的内置对象-8--4.date对象中-获取,设置日期时间的方法; 获取,设置年月日时分秒及星期的方法;

    学习目标 1.掌握创建日期对象的方法 2.掌握date对象中获取日期时间的方法 3.掌握date对象中设置日期时间的方法 如何创建一个日期对象 语法:new Date(); 功能:创建一个日期时间对象 ...

  7. Shell获取字符串长度的多种方法总结

    摘自:https://www.jb51.net/article/121290.htm 前言 我们在日常工作中,对于求字符串操作在shell脚本中很常用,实现的方法有很多种,下面就来给大家归纳.汇总了求 ...

  8. JS获取当前日期和时间的方法,并按照YYYY-MM-DD格式化

    Js获取当前日期时间及其它操作 var myDate = new Date(); myDate.getYear();        //获取当前年份(2位) myDate.getFullYear(); ...

  9. PHP获取当前日期和时间格式化方法

    使用函式 date() 实现 <?php echo $showtime=date("Y-m-d H:i:s");?> 显示的格式: 年-月-日 小时:分钟:妙 相关时间 ...

随机推荐

  1. Fiddler实战深入研究(二)[转载]

    Fiddler实战深入研究(二) 阅读目录 Fiddler不能捕获chrome的session的设置 理解数据包统计 请求重定向(AutoResponder) Composer选项卡 Filters选 ...

  2. Nginx的两种负载均衡搭建(Tomcat版)

    前言 Nginx的负载均衡一般采用upstream来实现,但是,还有另一种文件拓展的方式,同样可以实现负载均衡. 一.一般的负载均衡 upstream my_server { server local ...

  3. Strut2的配置文件strust.xml报错:Package Action extends undefined package struts-default

    struts.xml的警告信息,是需要联网验证dtd是否符合规范,只要配置成本地的dtd就会消失, 配置方式请看: 详细请看http://www.cnblogs.com/liuyangfirst/p/ ...

  4. python读取文件另存为

    fr = open(filename_r,encoding='cp852') w2 = open(filename_w,'a')#a代表追加 w代表重写 for line in fr: w2.writ ...

  5. Android中Activity启动过程探究

    首先追溯到Activity的启动,随便启动一个自己写的demo项目,使用DDMS进行debug标记,然后在Debug中把主线程暂停,可以看到调用栈.如下图所示: 于是我们先看android.app.A ...

  6. 被“1”和“l”给坑了

    由于输入法的原因,导致小写的英文字母“L”和阿拉伯数字“1”长得非常像,在写秘钥的时候很容易把看错.由于对方发秘钥的时候给的是图片,而且不太清晰,手动输入的时候把“1”写成“l”了,对了好几遍秘钥也没 ...

  7. crosss compile VLC with OpenMAX on ARM board(RockChip RK3399),in order to use Hard Acceleration when decode video

    reference:http://www.x90x90x90.com/en/raspberry-pi-3-howto-compile-vlc-with-hardware-acceleration/ 1 ...

  8. golang array, slice, string笔记

    本来想写一篇关于golang io的笔记,但是在学习io之前必须了解array, slice, string概念,因此将在下篇写golang io.   array: 数组的长度是该数组类型的一部分, ...

  9. linux系统编程:setjmp和longjmp函数用法

    #include <stdio.h> #include <setjmp.h> //jmp_buf:数组,保存栈信息即运行环境 jmp_buf buf; double Divid ...

  10. SQL Server 2016最值得关注的10大新特性

    全程加密技术(Always Encrypted) 全程加密技术(Always Encrypted)支持在SQL Server中保持数据加密,只有调用SQL Server的应用才能访问加密数据.该功能支 ...