#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. Part 4 - Authentication(14-16)

    from django.conf.urls import url from django.contrib import admin from django.contrib.auth import vi ...

  2. 处理jQuery选择器中的特殊符号,如(、#等

    前几天解决一个外网问题,客服反馈页面数据加载不出来,首先看一下服务端日志也没报错异常,自己测试了一下,在chrome的Console发现有js报错,原来是js报错导致的数据加载不出来. 调试了一番,发 ...

  3. Navicat for oracle cannot load OCI DLL

    Navicat for oracle 提示 cannot load OCI DLL87,126,193 instant client package is required for basic and ...

  4. 如何在MAC下安装Myeclipse2015真的很虐心!!!!!!!!!!

    最近笔者换了一个新的笔记本,mac pro 因为同学说大公司的web开发都是写在Linux操作系统下的,所以我决定搞一个,但是装软件就是很困难啊!找了大量资料发现都不全,最后,终于搞好了,分享给同样虐 ...

  5. HDU 2393 Higher Math (判断直角三角形)

    题意:给定三个边,判断是不是直角三角形. 析:水题,勾股定理... 代码如下: #include <iostream> #include <cstdio> #include & ...

  6. STL中的Vector相关用法

    STL中的Vector相关用法 标准库vector类型使用需要的头文件:#include <vector>. vector 是一个类模板,不是一种数据类型,vector<int> ...

  7. How Many Tables HDOJ

    How Many Tables Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)T ...

  8. Useful Field of View (UFOV)

    IE8不支持canvas,使用excanvas.js,js代码需要放在window.onload=function(){...}内,$(docuemnt).ready(function(){...}) ...

  9. java虚拟机加载系统环境变量到内存中

    JVM在启动的时候,会将环境变量,转换到 系统属性 里面.可以通过System.getProperty("");来获取.catalina.home属性,就是运行tomcat的JVM ...

  10. swipe js bug

    最近因为要写新的mobile site页面,有好几个页面上面必须用到photo slider. 使用插件: /* * Swipe 2.0 * * Brad Birdsall * Copyright 2 ...