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这 ...
随机推荐
- day06—JavaScript之闭包
转行学开发,代码100天——2018-03-22 第一次听说“闭包”这个词,还是在2015年某个深夜在听一节腾讯课堂的公开课上,当时老师讲什么已经没有清晰的记忆了,只知道是一次web的开发课程. 过了 ...
- 慎用create table as select,一定要注意默认值的问题
再做一些数据迁移时候,很多人会使用create table as select * from table where id=-1的方式来年建立一摸一样的表,但是这样做有个很大的弊端,不能将原表中的d ...
- jenkins之启动与关闭
jenkins可以通过内置的应用服务器或者借助其他应用服务器启动 目录 1.启动jenkins 2.关闭jenkins 3.重启jenkins 4.重新加载jenkins配置信息 1.启动jenkin ...
- 数据挖掘与CRM
数据挖掘与CRM 现在的数据挖掘项目多数都是游击战,这边挖一挖那边挖一挖,挖到最后还是一场空,还落了个"忽悠"绰号:回想数据挖掘的一个标准流程,那只是一个数据挖掘类项目的标杆而已, ...
- Unity3D架构之PureMVC
之前了解过UI实现框架大多是用MVC架构的,才听说有这么一个基于MVC的跨平台开源框架叫PureMVC,前几天用到了做了一下,写一写分析总结官网位置:http://puremvc.org/ PureM ...
- parameterType和resultType配置错误
自己在写mapper.xml的时候 吧parameterType和resultType的两个类搞混了 对调了一下 以至于查询了半天查询不出结果 <select id="findPat ...
- Spring Cloud Stream 进行服务之间的通讯
Spring Cloud Stream Srping cloud Bus的底层实现就是Spring Cloud Stream,Spring Cloud Stream的目的是用于构建基于消息驱动(或事件 ...
- 19、NumPy——线性代数
NumPy 线性代数 NumPy 提供了线性代数函数库 linalg,该库包含了线性代数所需的所有功能,可以看看下面的说明: 函数 描述 dot 两个数组的点积,即元素对应相乘. vdot 两个向量的 ...
- Android手机、电视(盒子) 打开ADB调试 一览表
手机.电视(盒子) 打开ADB调试 一览表 一.手机打开ADB调试方法 序号 名称 描述 方式 1 华为手机 EMUI 1.设置 ->关于手机-> 版本号 点击(4~5次)2.返回设置 - ...
- 并行开发 2.task
原文:8天玩转并行开发——第二天 Task的使用 在我们了解Task之前,如果我们要使用多核的功能可能就会自己来开线程,然而这种线程模型在.net 4.0之后被一种称为基于 “任务的编程模型”所冲击, ...