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这 ...
随机推荐
- LookupError: "gw_lt" is not among the defined enum values
LookupError: "XXX" is not among the defined enum value 查找错误:“xxx”不在定义的枚举值中 model.py中没有增加对应 ...
- Mongodb php扩展及安装
Mongodb php扩展 Mongodb安装 1: 下载mongodb www.mongodb.org 下载最新的stable版 2: 解压文件 3: ...
- 牛顿法求极值及其Python实现
最初对于牛顿法,我本人是一脸懵的.其基本原理来源于高中知识.在如下图所示的曲线,我们需要求的是f(x)的极值: 对于懵的原因,是忘记了高中所学的点斜式,直接贴一张高中数学讲义: 因为我们一路沿着x轴去 ...
- [Bzoj1047][HAOI2007]理想的正方形(ST表)
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1047 题目虽然有一个n的限制,但求二维区间最值首先想到的还是RMQ,但是如果按照往常RM ...
- 数据导出 写入到excle文件
import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.poi ...
- Vue2.0源码阅读笔记(四):nextTick
在阅读 nextTick 的源码之前,要先弄明白 JS 执行环境运行机制,介绍 JS 执行环境的事件循环机制的文章很多,大部分都阐述的比较笼统,甚至有些文章说的是错误的,以下为个人理解,如有错误, ...
- SpringCloud-Eureka-Provider&Consumer
Eureka-Provider 服务的提供者 新建一个服务提供者项目 1.导入pom文件 <properties> <java.version>1.8</java.ver ...
- day50 初识JavaScript
一.背景介绍 (一)web开发的三种样式: 结构:HTML:从语义的角度,描述页面结构 样式:CSS:从审美的角度,描述样式(美化页面) 行为(动态)JavaScript:从交互的角度,描述行为(用于 ...
- 2018-7-24-WPF-渲染级别
title author date CreateTime categories WPF 渲染级别 lindexi 2018-07-24 18:46:27 +0800 2018-04-20 16:26: ...
- RESET - 把一个运行时参数值恢复为缺省值
SYNOPSIS RESET name RESET ALL DESCRIPTION 描述 RESET 将运行时参数恢复为缺省值. RESET 是下面语句的一个变种 SET parameter TO D ...