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这 ...
随机推荐
- day05—JavaScript之函数调用
转行学开发,代码100天——2018-03-21 JavaScript中的函数调用有4种方式: 方式一:直接通过函数名调用 在 HTML 中默认的全局对象是 HTML 页面本身,所以函数是属于 HTM ...
- 【FICO系列】SAP FICO模块-固定资产月结的注意点
公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[FICO系列]SAP FICO模块-固定资产月 ...
- Locally weighted regression algorithm
在此引出另一种模型:Locally weighted regression algorithm(LWLR/LWR),通过名字我们可以推断,这是一种更加关注局部变化的模型.的确如此,在普通的linear ...
- Java中的基本类型和包装类型区别
首先看一下几个测试题,验证一下java中对基本类型和包装类型的理解,看看最后输出的答案对不对,答案在这篇博客中哦: // 第一题: 基本类型和包装类型 int a = 100; Integer b = ...
- 20190821 On Java8 第十一章 内部类
第十一章 内部类 一个定义在另一个类中的类,叫作内部类. 链接外部类 内部类是一种名字隐藏和组织代码的模式. 内部类拥有其外围类的所有元素的访问权. 内部类 .this 和 .new的使用 this: ...
- python线程理论
一.什么是线程 线程:顾名思义,就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程 所以,进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才 ...
- JavaScript的变量作用域
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Debian(Linux)+XAMPP(LAMPP)+Zend Studio + PHP +XDebug 完整的开发环境配置方法。 转摘:http://www.cnblogs.com/kungfupanda/archive/2010/11/25/1887812.html
经历了3天左右的挣扎,终于在Linux下将 php开发工具 Zend Studio 的 xdebug安装成功,分享如下: 1,装XAMPP,安装方法链接如下:这里假设XAMPP的安装路径为:/opt/ ...
- JVM(11)之 G1收集器
开发十年,就只剩下这套架构体系了! >>> 在前两篇博文中讲解了新生代和年老代的收集器,在本篇博文中介绍一个收集范围涵盖整个堆的收集器--G1收集器. 先讲讲G1收集器的特点, ...
- Java 8实战之读书笔记二:基础知识
好记性不如烂笔头,整理一些个人觉得比较重要的东西. 一.基础知识 第1章 为什么要关心Java 8 Java 8提供了一个新的API(称为"流", Stream),它支持许多处理数 ...