C#获取获取北京时间多种方法
#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#获取获取北京时间多种方法的更多相关文章
- 【机房收费系统 4】:VB获取标准北京时间,免除时间误差
导读:这又是师傅给我指出的一个问题,说实话,其实开始根本没有当回事,觉得麻烦,可是,等我完成了获取标准北京时间后,我发现,这一步,是必须的.谢谢师傅对我的严格要求,让我一步一步的成长起来! 一.事件缘 ...
- java中获取日期和时间的方法总结
1.获取当前时间,和某个时间进行比较.此时主要拿long型的时间值. 方法如下: 要使用 java.util.Date .获取当前时间的代码如下 Date date = new Date(); da ...
- PHP获取当前日期和时间的方法
PHP获取当前日期和时间的方法 来源:wikiHow 时间:2014-12-04 14:49:45 阅读数:7240 分享到:0 [导读] PHP是用来创建网络中动态内容的常见语言,因此PHP ...
- WPF 获取系统 DPI 的多种方法
原文:WPF 获取系统 DPI 的多种方法 WPF 获取系统 DPI 的多种方法 由于 WPF 的尺寸单位和系统的 DPI 相关,我们有时需要获取 DPI 值来进行一些界面布局的调整,本文汇总了一些 ...
- cocos2d-x在win32和iOS、android下获取当前系统时间的方法
最近在游戏里要显示当前系统时间的功能,网上一搜很多写着获取的方法,大都是如下 struct cc_timeval now; CCTime::gettimeofdayCocos2d(&now, ...
- JavaScript中的内置对象-8--4.date对象中-获取,设置日期时间的方法; 获取,设置年月日时分秒及星期的方法;
学习目标 1.掌握创建日期对象的方法 2.掌握date对象中获取日期时间的方法 3.掌握date对象中设置日期时间的方法 如何创建一个日期对象 语法:new Date(); 功能:创建一个日期时间对象 ...
- Shell获取字符串长度的多种方法总结
摘自:https://www.jb51.net/article/121290.htm 前言 我们在日常工作中,对于求字符串操作在shell脚本中很常用,实现的方法有很多种,下面就来给大家归纳.汇总了求 ...
- JS获取当前日期和时间的方法,并按照YYYY-MM-DD格式化
Js获取当前日期时间及其它操作 var myDate = new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); ...
- PHP获取当前日期和时间格式化方法
使用函式 date() 实现 <?php echo $showtime=date("Y-m-d H:i:s");?> 显示的格式: 年-月-日 小时:分钟:妙 相关时间 ...
随机推荐
- idea开发工具下报Set language level to 6-@Override in interfaces的解决方法
idea开发工具下报Set language level to 6-@Override in interfaces的解决方法 实现接口时报如下错误:Set language level to 6-@O ...
- 2018.10.01 bzoj3237: [Ahoi2013]连通图(cdq分治+并查集)
传送门 cdq分治好题. 对于一条边,如果加上它刚好连通的话,那么删掉它会有两个大集合A,B.于是我们先将B中禁用的边连上,把A中禁用的边禁用,再递归处理A:然后把A中禁用的边连上,把B中禁用的边禁用 ...
- python创建二维数组
c=[[0]*3 for i in range(3)] c=[[0 for i in range(3)] for i in range(3)]
- python文件操作,读取,修改,合并
# -*- coding:utf-8 -*- ''' 从11c开始提取 ''' import re import numpy as np import os year = '17A' ss=" ...
- ArcGIS Desktop Python add-ins 共享和安装插件
1) 共享和安装插件 共享Python插件的关键是.esriaddin文件;为了获取该插件功能,其他用户只要在本机执行安装操作或通过网络引用该插件就可以. ArcGIS插件安装工具 当用户双击一个 ...
- (转)code first基础
转自:http://tech.it168.com/a2011/0719/1220/000001220362_all.shtml [IT168 技术]随着.NET 4.0时代的到来,开发者越来越关注如何 ...
- java代码中存在的Big Endian 和 Little Endian
Big Endian 和 Little Endian 详解 Java中的Big(Little)-endian问题的一种解决方法 主机序和网络序 很重要很重要 几种ip存放形式 Big-Endian和 ...
- El中调用java静态方法
最近在项目中遇到需要调用静态方法的问题,形如: <c:forEach items="beans" var="bean"> <p>总数:$ ...
- ThinkPad T430i,如何将WIN8换成WIN7???
1. 启动时不断点击键盘上的F1键,进入BIOS 界面选择“Restart”→把 “OS Optimized Default”设置为 “disabled” ,(OS Optimized Default ...
- [LeetCode] Climbing Stairs (Sequence DP)
Climbing Stairs https://oj.leetcode.com/problems/climbing-stairs/ You are climbing a stair case. It ...