#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. HTML5/CSS3基础

    1. HTML 1.1 什么是HTML HTML是用来制作网页的标记语言 HTML是Hypertext Markup Language的英文缩写,即超文本标记语言 HTML语言是一种标记语言,不需要编 ...

  2. list集合如何对里面的元素进行排序

    Collections 是集合的公共类,提供各种工具,其中提供了排序方法. Collections.sort(),方法两个参数,1,要排序的集合,2.排序方式 下面是匿名内部类,实现了排序借口,你也可 ...

  3. 实体类在set字段时报空指针异常

    实体类在set字段时报空指针异常的原因: T_Entry entry=null;entry.setGeneName("1212");entry.setEntryName(" ...

  4. VHDL实例化过程

    第二步:建立一个名为MUX_0的乘法器 第三步:在程序中例化,看以下程序. -- 该程序用来实现复数的乘法,端口分别定义的复数的 -- 输入的实部和虚部和输出的实部和虚部 LIBRARY IEEE; ...

  5. 20155320 2016-2017-2 《Java程序设计》第7周学习总结

    20155320 2016-2017-2 <Java程序设计>第7周学习总结 教材学习内容总结 时间与日期 认识时间与日期 时间的度量 GMT(Greenwich Mean Time)时间 ...

  6. linux的客户端安装步骤配置

    现有一个***.tar.gz的客户端软件,现在客户端安装步骤如下 说明:此软件是一个网络客户端认证软件,因为采用虚拟机中的linux主机,所以此主机的网路配置从只能使用Bridge模式,而不能使用NA ...

  7. 快速学会在JSP中使用EL表达式

    在没有学会EL表达式之前,我们想在JSP文件中获取servlet或者其他JSP页面传来的值,通常都是在JSP页面中编写java代码来实现.而在jsp页面编写Java 代码,这种做法时不规范的,将会产生 ...

  8. ActiveMq 总结(一)

    1. 背景 当前,CORBA.DCOM.RMI等RPC中间件技术已广泛应用于各个领域.但是面对规模和复杂度都越来越高的分布式系统,这些技术也显示出其局限性:(1)同步通信:客户发出调用后,必须等待服务 ...

  9. KVM NAT网络模式配置

    NAT方式原理 NAT方式是kvm安装后的默认方式.它支持主机与虚拟机的互访,同时也支持虚拟机访问互联网,但不支持外界访问虚拟机. 检查当前的网络设置: #virsh net-list --all N ...

  10. c#使用NPOI快速导出到Excel

    接上篇博文<C#快速导出到excel>:由于此种方法不能导出成.xlsx格式,为解决此问题,本次分享使用NPOI. 参考:https://www.cnblogs.com/lazyneal/ ...