C# 调用windows时间同步服务获取准确时间
//创建一个Daytime类代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices; public class Daytime
{
// Internet Time Server class by Alastair Dallas 01/27/04 // Number of seconds
private const int THRESHOLD_SECONDS = ;
// that Windows clock can deviate from NIST and still be okay //Server IP addresses from
//http://www.boulder.nist.gov/timefreq/service/time-servers.html
private static string[] Servers = {
"129.6.15.28",
"129.6.15.29",
"132.163.4.101",
"132.163.4.102",
"132.163.4.103",
"128.138.140.44",
"192.43.244.18",
"131.107.1.10",
"66.243.43.21",
"216.200.93.8",
"208.184.49.9",
"207.126.98.204",
"205.188.185.33"
//65.55.21.15time.windows.com微软时间同步服务器
};
public static string LastHost = ""; public static DateTime LastSysTime;
public static DateTime GetTime()
{
//Returns UTC/GMT using an NIST server if possible,
// degrading to simply returning the system clock //If we are successful in getting NIST time, then
// LastHost indicates which server was used and
// LastSysTime contains the system time of the call
// If LastSysTime is not within 15 seconds of NIST time,
// the system clock may need to be reset
// If LastHost is "", time is equal to system clock string host = null;
DateTime result = default(DateTime); LastHost = "";
foreach (string host_loopVariable in Servers)
{
host = host_loopVariable;
result = GetNISTTime(host);
if (result > DateTime.MinValue)
{
LastHost = host;
break; // TODO: might not be correct. Was : Exit For
}
} if (string.IsNullOrEmpty(LastHost))
{
//No server in list was successful so use system time
result = DateTime.UtcNow;
} return result;
} public static int SecondsDifference(DateTime dt1, DateTime dt2)
{
TimeSpan span = dt1.Subtract(dt2);
return span.Seconds + (span.Minutes * ) + (span.Hours * );
} public static bool WindowsClockIncorrect()
{
DateTime nist = GetTime();
if ((Math.Abs(SecondsDifference(nist, LastSysTime)) > THRESHOLD_SECONDS))
{
return true;
}
return false;
} private static DateTime GetNISTTime(string host)
{
//Returns DateTime.MinValue if host unreachable or does not produce time
DateTime result = default(DateTime);
string timeStr = null; try
{
StreamReader reader = new StreamReader(new TcpClient(host, ).GetStream());
LastSysTime = DateTime.UtcNow;
timeStr = reader.ReadToEnd();
reader.Close();
}
catch (SocketException ex)
{
//Couldn't connect to server, transmission error
Debug.WriteLine("Socket Exception [" + host + "]");
return DateTime.MinValue;
}
catch (Exception ex)
{
//Some other error, such as Stream under/overflow
return DateTime.MinValue;
} //Parse timeStr
if ((timeStr.Substring(, ) != "UTC(NIST)"))
{
//This signature should be there
return DateTime.MinValue;
}
if ((timeStr.Substring(, ) != ""))
{
//Server reports non-optimum status, time off by as much as 5 seconds
return DateTime.MinValue;
//Try a different server
} int jd = int.Parse(timeStr.Substring(, ));
int yr = int.Parse(timeStr.Substring(, ));
int mo = int.Parse(timeStr.Substring(, ));
int dy = int.Parse(timeStr.Substring(, ));
int hr = int.Parse(timeStr.Substring(, ));
int mm = int.Parse(timeStr.Substring(, ));
int sc = int.Parse(timeStr.Substring(, )); if ((jd < ))
{
//Date is before 1900
return DateTime.MinValue;
}
if ((jd > ))
yr += ;
else
yr += ; return new DateTime(yr, mo, dy, hr, mm, sc);
} [StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public Int16 wYear;
public Int16 wMonth;
public Int16 wDayOfWeek;
public Int16 wDay;
public Int16 wHour;
public Int16 wMinute;
public Int16 wSecond;
public Int16 wMilliseconds;
}
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 GetSystemTime(ref SYSTEMTIME stru);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 SetSystemTime(ref SYSTEMTIME stru); public static void SetWindowsClock(DateTime dt)
{
//Sets system time. Note: Use UTC time; Windows will apply time zone SYSTEMTIME timeStru = default(SYSTEMTIME);
Int32 result = default(Int32); timeStru.wYear = (Int16)dt.Year;
timeStru.wMonth = (Int16)dt.Month;
timeStru.wDay = (Int16)dt.Day;
timeStru.wDayOfWeek = (Int16)dt.DayOfWeek;
timeStru.wHour = (Int16)dt.Hour;
timeStru.wMinute = (Int16)dt.Minute;
timeStru.wSecond = (Int16)dt.Second;
timeStru.wMilliseconds = (Int16)dt.Millisecond;
result = SetSystemTime(ref timeStru);
}
}
调用方法:
Daytime.GetTime().ToLocalTime() //这个就是同步后准确的时间,DateTime类型的。
C# 调用windows时间同步服务获取准确时间的更多相关文章
- 根据Time Protocol从NIST Internet Time Servers获取准确时间
Time Protocol(RFC-868)是一种非常简单的应用层协议:它返回一个32位的二进制数字,这个数字描述了从1900年1月1日0时0分0秒到现在的秒数,服务器在TCP的37号端口监听时间协议 ...
- java调用windows的wmi获取设备性能数据
java调用windows的wmi获取监控数据(100%纯java调用windows的wmi获取监控数据) 转:http://my.oschina.net/noahxiao/blog/73163 纯j ...
- 阿里云windows时间同步服务地址
偶然发现的, 记录一下 ntp1.aliyun.com
- 玩转Windows服务系列——Windows服务启动超时时间
最近有客户反映,机房出现断电情况,服务器的系统重新启动后,数据库服务自启动失败.第一次遇到这种情况,为了查看是不是断电情况导致数据库文件损坏,从客户的服务器拿到数据库的日志,进行分析. 数据库工作机制 ...
- 时区之痒 - 从手机GPS模块获取的时间,真的是北京时间么?
去年互联网地图行业开始引入众包模式,国内比较大的地图商,比如四维图新.高德地图.百度地图纷纷开始推出UGC应用,众包给用户采集门址.公交站等信息,并按照工作量给与采集者一定的回报.我曾经玩过某德推出的 ...
- RAC集群时间同步服务
集群时间同步服务在集群中的两个 Oracle RAC 节点上执行以下集群时间同步服务配置.Oracle Clusterware 11g 第 2 版及更高版本要求在部署了 Oracle RAC 的集群的 ...
- Dynamics CRM 后台通过组织服务获取时间字段值的准确转换
做CRM开发的都知道,在系统时间字段的处理上是有讲究的,因为数据库中存的是UTC时间,CRM的界面时间字段会根据个人设置中的时区以及格式自动调整,这是最基本的一面,那还有很多使用时间的场景,比如脚本使 ...
- Windows下获取高精度时间注意事项
Windows下获取高精度时间注意事项 [转贴 AdamWu] 花了很长时间才得到的经验,与大家分享. 1. RDTSC - 粒度: 纳秒级 不推荐优势: 几乎是能够获得最细粒度的计数器抛弃理由: ...
- 一个 C# 获取高精度时间类(调用API QueryP*)
如果你觉得用 DotNet 自带的 DateTime 获取的时间精度不够,解决的方法是通过调用 QueryPerformanceFrequency 和 QueryPerformanceCounter这 ...
随机推荐
- js中return;、return true、return false的区别
一.返回控制与函数结果, 语法为:return 表达式; 语句结束函数执行,返回调用函数,而且把表达式的值作为函数的结果 二.返回控制, 无函数结果,语法为:return; 在大多数情况下,为事件 ...
- rpm --qf 命令
1. 环境准备: sudo apt-get install rpm (Ubuntu系统) wget ftp://rpmfind.net/linux/fedora-secondary/developme ...
- Bootstrap 学习笔记7 模态框插件
网站弹出框使用: 基本使用: <!-- 模态框的声明 --> <div class="modal" id="myModal" tabindex ...
- Pikachu漏洞练习平台实验——不安全的文件下载和上传(七)
1.不安全的文件下载 1.1.概述 文件下载功能在很多web系统上都会出现,一般我们当点击下载链接,便会向后台发送一个下载请求,一般这个请求会包含一个需要下载的文件名称,后台在收到请求后 会开始执行下 ...
- Java笔记——Map集合
Map集合接口 Map集合与Collection不是从属关系,是平级的 Map集合的映射特点 一个映射不能包含重复的键,由此键只能允许有一个空null 每个键最多只能和一个值对应 值可以重复,由此值允 ...
- [暑假集训Day3T2]骑士问题
标准的广搜. 采用队列保存形态,如果不会广搜的可以多看看PJ知识点.由于输入多组数据,每次标记数组要清空,每次队列元素也都要清空. 参考代码如下: #include<iostream> # ...
- 浅谈XML涉及到的常见技术(编写+解析)
xml:即可扩展标记语言,用于描述关系型数据,也经常用作软件的配置文件: 1,编写xml文档一般基于一个约束文档,该文档用于规定xml的书写规范,常用的约束技术有 (1)XML ...
- 全文检索引擎sphinx 与 Elasticsearch 索引速度对比
sphinx的特色之一是建立索引速度快,最近转投Elasticsearch后,一直想做个对比,网上资料常见说法是10倍的差距. 测试环境 硬件:单核,2G内存的E5-2630 虚拟机 操作系统:Cen ...
- Windows server 2012/2016系统安装zabbix3.2客户端
一. 上传zabbix客户端文件 将zabbix_agents_3.2.0.win.zip文件上传至服务器的指定路径. 二. 解压并修改相关信息 解压已上传的客户端文件,在co ...
- vue,一路走来(2)--路由vue-router
安装 Mint UI cnpm install mint-ui --save 如果你的项目会用到 Mint UI 里较多的组件,最简单的方法就是把它们全部引入.此时需要在入口文件 main.js 中: ...