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这 ...
随机推荐
- selenium自动化测试之【数据驱动测试】
数据驱动测试是自动化测试的主流设计模式之一,相同的测试脚本使用不同的测试数据来执行,测试数据和测试行为进行了完全的分离,这样的测试脚本设计模式称为数据驱动.实施数据驱动测试的步骤:1.编写测试脚本,脚 ...
- Ubuntu下使用boost例子
http://blog.csdn.net/dotphoenix/article/details/8459277 1. 安装boost库 sudo apt-get install libboost-al ...
- SPOJ NICEBTRE - Nice Binary Trees(树 先序遍历)
传送门 Description Binary trees can sometimes be very difficult to work with. Fortunately, there is a c ...
- Ural Amount of Degrees(数位dp)
传送门 Amount of Degrees Time limit: 1.0 secondMemory limit: 64 MB Description Create a code to determi ...
- LinkedList -链表集合
package cn.learn.collection; import java.util.LinkedList; import java.util.Queue; /* java.util.xxx A ...
- ac自动机(tree+kmp模板)
Keywords Search Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others ...
- 6、numpy——高级索引
NumPy 比一般的 Python 序列提供更多的索引方式.除了之前看到的用整数和切片的索引外,数组可以由整数数组索引.布尔索引及花式索引. 1.整数数组索引 1.1 以下实例获取数组中(0,0),( ...
- python学习第十六天集合的关系测试
在做数据分析的时候,要对一个集合分析,而且分析多个集合的之间的关系分析,那么用传统的循环的比较麻烦,集合提供很多方法,很容易比较多个集合的关系,并集,交集,差集,对称差集等. n1={1,2,4,6} ...
- sql插入语句笔记
使用INSERT插入数据行 [一次插入一行数据] 全写: INSERT INTO renshi (name, sex, age ,tel) VALUES ('胡大姐','女','35','13 ...
- day65--mysql数据库--索引、慢日志、分页
---恢复内容开始--- 一.索引 (一)介绍: 数据库中专门用于帮助用户快速查找数据的一种数据结构.类似于字典中的目录,查找字典内容时可以根据目录查找到数据的存放位置吗,然后直接获取. (二)作用: ...