C# 调用windows时间同步服务获取准确时间

1//创建一个Daytime类代码如下:using System; 2using System.Collections; 3using System.Collections.Generic; 4using System.Data; 5using System.Diagnostics; 6using System.IO; 7using System.Net; 8using System.Net.Sockets; 9using System.Runtime.InteropServices; 10 11public class Daytime 12{ 13 // Internet Time Server class by Alastair Dallas 01/27/04 14 15 // Number of seconds 16 private const int THRESHOLD_SECONDS = 15; 17 // that Windows clock can deviate from NIST and still be okay 18 19 //Server IP addresses from 20 //http://www.boulder.nist.gov/timefreq/service/time-servers.html 21 private static string[] Servers = { 22 "129.6.15.28", 23 "129.6.15.29", 24 "132.163.4.101", 25 "132.163.4.102", 26 "132.163.4.103", 27 "128.138.140.44", 28 "192.43.244.18", 29 "131.107.1.10", 30 "66.243.43.21", 31 "216.200.93.8", 32 "208.184.49.9", 33 "207.126.98.204", 34 "205.188.185.33" 35//65.55.21.15time.windows.com微软时间同步服务器 36 }; 37 public static string LastHost = ""; 38 39 public static DateTime LastSysTime; 40 public static DateTime GetTime() 41 { 42 //Returns UTC/GMT using an NIST server if possible, 43 // degrading to simply returning the system clock 44 45 //If we are successful in getting NIST time, then 46 // LastHost indicates which server was used and 47 // LastSysTime contains the system time of the call 48 // If LastSysTime is not within 15 seconds of NIST time, 49 // the system clock may need to be reset 50 // If LastHost is "", time is equal to system clock 51 52 string host = null; 53 DateTime result = default(DateTime); 54 55 LastHost = ""; 56 foreach (string host_loopVariable in Servers) 57 { 58 host = host_loopVariable; 59 result = GetNISTTime(host); 60 if (result > DateTime.MinValue) 61 { 62 LastHost = host; 63 break; // TODO: might not be correct. Was : Exit For 64 } 65 } 66 67 if (string.IsNullOrEmpty(LastHost)) 68 { 69 //No server in list was successful so use system time 70 result = DateTime.UtcNow; 71 } 72 73 return result; 74 } 75 76 public static int SecondsDifference(DateTime dt1, DateTime dt2) 77 { 78 TimeSpan span = dt1.Subtract(dt2); 79 return span.Seconds + (span.Minutes * 60) + (span.Hours * 360); 80 } 81 82 public static bool WindowsClockIncorrect() 83 { 84 DateTime nist = GetTime(); 85 if ((Math.Abs(SecondsDifference(nist, LastSysTime)) > THRESHOLD_SECONDS)) 86 { 87 return true; 88 } 89 return false; 90 } 91 92 private static DateTime GetNISTTime(string host) 93 { 94 //Returns DateTime.MinValue if host unreachable or does not produce time 95 DateTime result = default(DateTime); 96 string timeStr = null; 97 98 try 99 { 100 StreamReader reader = new StreamReader(new TcpClient(host, 13).GetStream()); 101 LastSysTime = DateTime.UtcNow; 102 timeStr = reader.ReadToEnd(); 103 reader.Close(); 104 } 105 catch (SocketException ex) 106 { 107 //Couldn't connect to server, transmission error 108 Debug.WriteLine("Socket Exception [" + host + "]"); 109 return DateTime.MinValue; 110 } 111 catch (Exception ex) 112 { 113 //Some other error, such as Stream under/overflow 114 return DateTime.MinValue; 115 } 116 117 //Parse timeStr 118 if ((timeStr.Substring(38, 9) != "UTC(NIST)")) 119 { 120 //This signature should be there 121 return DateTime.MinValue; 122 } 123 if ((timeStr.Substring(30, 1) != "0")) 124 { 125 //Server reports non-optimum status, time off by as much as 5 seconds 126 return DateTime.MinValue; 127 //Try a different server 128 } 129 130 int jd = int.Parse(timeStr.Substring(1, 5)); 131 int yr = int.Parse(timeStr.Substring(7, 2)); 132 int mo = int.Parse(timeStr.Substring(10, 2)); 133 int dy = int.Parse(timeStr.Substring(13, 2)); 134 int hr = int.Parse(timeStr.Substring(16, 2)); 135 int mm = int.Parse(timeStr.Substring(19, 2)); 136 int sc = int.Parse(timeStr.Substring(22, 2)); 137 138 if ((jd < 15020)) 139 { 140 //Date is before 1900 141 return DateTime.MinValue; 142 } 143 if ((jd > 51544)) 144 yr += 2000; 145 else 146 yr += 1900; 147 148 return new DateTime(yr, mo, dy, hr, mm, sc); 149 } 150 151 [StructLayout(LayoutKind.Sequential)] 152 public struct SYSTEMTIME 153 { 154 public Int16 wYear; 155 public Int16 wMonth; 156 public Int16 wDayOfWeek; 157 public Int16 wDay; 158 public Int16 wHour; 159 public Int16 wMinute; 160 public Int16 wSecond; 161 public Int16 wMilliseconds; 162 } 163 [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] 164 private static extern Int32 GetSystemTime(ref SYSTEMTIME stru); 165 [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] 166 private static extern Int32 SetSystemTime(ref SYSTEMTIME stru); 167 168 public static void SetWindowsClock(DateTime dt) 169 { 170 //Sets system time. Note: Use UTC time; Windows will apply time zone 171 172 SYSTEMTIME timeStru = default(SYSTEMTIME); 173 Int32 result = default(Int32); 174 175 timeStru.wYear = (Int16)dt.Year; 176 timeStru.wMonth = (Int16)dt.Month; 177 timeStru.wDay = (Int16)dt.Day; 178 timeStru.wDayOfWeek = (Int16)dt.DayOfWeek; 179 timeStru.wHour = (Int16)dt.Hour; 180 timeStru.wMinute = (Int16)dt.Minute; 181 timeStru.wSecond = (Int16)dt.Second; 182 timeStru.wMilliseconds = (Int16)dt.Millisecond; 183 result = SetSystemTime(ref timeStru); 184 } 185} 186 187 188 189调用方法: 190Daytime.GetTime().ToLocalTime() //这个就是同步后准确的时间,DateTime类型的。
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java日期时间API系列31

  时间戳是指格林威治时间1970年01月01日00时00分00秒起至现在的总毫秒数,是所有时间的基础,其他时间可以通过时间戳转换得到。Java中本来已经有相关获取时间戳的方法,Java8后增加新的类Instant等专用于处理时间戳问题。 1获取时间戳的方法和性能对比1.1获取时间戳方法Java8以前