C# 同步更新系统时间
前言
在定位用户问题时,发现有些电脑,会出现系统时间不是最新的问题。
可能原因:
- 取消了勾选服务器时间同步
- 当前安装的系统,是一个未知来源系统,导致系统时间更新失败
而系统时间不正确,会导致IE选项-证书,校验不通过~
更新系统时间
1. 连接时间服务器
时间服务器列表(推荐): string[] timeHosts = { "time.windows.com", "time.nist.gov" };
/// <summary>
/// 连接时间服务器
/// </summary>
/// <param name="socket">服务器接口</param>
/// <param name="startTime">开始时间</param>
/// <param name="errorMsg">错误信息</param>
/// <returns></returns>
private static bool TryConnectToTimeServer(out Socket socket, out DateTime startTime, out string errorMsg)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
socket.ReceiveTimeout = * ;//设置超时时间
errorMsg = string.Empty;
startTime = DateTime.Now; // 遍历时间服务器列表
foreach (string strHost in timeHosts)
{
try
{
// 记录开始的时间
startTime = DateTime.Now; var iphostinfo = Dns.GetHostEntry(strHost);
var ip = iphostinfo.AddressList[];
//建立IPAddress对象与端口,创建IPEndPoint节点:
int port = ;
var ipe = new IPEndPoint(ip, port);
//连接到服务器
socket.Connect(ipe);
// 如果连接到服务器就跳出
if (socket.Connected) break;
}
catch (Exception ex)
{
errorMsg = $"时间服务器连接失败!\r\n错误信息:{ex.Message}系统提示";
}
}
return socket.Connected;
}
2. 从服务器接收数据
/// <summary>
/// 从服务器接收数据
/// </summary>
/// <param name="socket"></param>
/// <returns></returns>
private static StringBuilder ReceiveMessageFromServer(Socket socket)
{
//SOCKET同步接受数据
byte[] receiveBytes = new byte[];
int nBytes, nTotalBytes = ;
StringBuilder sb = new StringBuilder();
System.Text.Encoding encoding = Encoding.UTF8; while ((nBytes = socket.Receive(receiveBytes, , , SocketFlags.None)) > )
{
nTotalBytes += nBytes;
sb.Append(encoding.GetString(receiveBytes, , nBytes));
} return sb;
}
3. 更新本地时间
/// <summary>
/// 更新系统时间
/// </summary>
/// <returns>更新结果</returns>
public static string UpdateSystemTime()
{
try
{
var connected = TryConnectToTimeServer(out Socket socket, out var startTime, out string errorMsg);
if (connected)
{
var receivedMsg = ReceiveMessageFromServer(socket);
socket.Close();
//切割字符串
string[] receiveMsgList = receivedMsg.ToString().Split(' ');
if (receiveMsgList.Length >= )
{
var dateTimeValue = receiveMsgList[] + " " + receiveMsgList[];
SetLocalTime(startTime, dateTimeValue);
}
}
else
{
return errorMsg;
}
}
catch (Exception e)
{
return $"函数{nameof(UpdateSystemTime)}执行异常,{e.Message}";
}
return "时间已同步";
}
/// <summary>
/// 设置系统时间
/// </summary>
/// <param name="startTime">请求服务器时的开始时间</param>
/// <param name="dateTimeValue">服务器返回的时间</param>
private static void SetLocalTime(DateTime startTime, string dateTimeValue)
{
// 得到开始到现在所消耗的时间
TimeSpan k = DateTime.Now - startTime;
// 减去中途消耗的时间
DateTime updatedUtcTime = Convert.ToDateTime(dateTimeValue).Subtract(-k); //处置北京时间 +8时
var updatedTime = updatedUtcTime.AddHours(); //转换System.DateTime到SystemTime
SystemTime systemTime = new SystemTime();
systemTime.FromDateTime(updatedTime); //调用Win32 API设置系统时间
Win32API.SetLocalTime(ref systemTime);
}
系统时间辅助类 & Win32API :
/// <summary>
/// 系统时间帮助类
/// </summary>
public struct SystemTime
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds; /// <summary>
/// 从System.DateTime转换。
/// </summary>
/// <param name="time">System.DateTime类型的时间。</param>
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}
/// <summary>
/// 转换为System.DateTime类型。
/// </summary>
/// <returns></returns>
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
/// <summary>
/// 静态方法。转换为System.DateTime类型。
/// </summary>
/// <param name="time">SYSTEMTIME类型的时间。</param>
/// <returns></returns>
public static DateTime ToDateTime(SystemTime time)
{
return time.ToDateTime();
}
} /// <summary>
/// 系统更新时间DLL
/// </summary>
public class Win32API
{
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime Time);
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SystemTime Time);
}
Github地址:IE环境修复工具
C# 同步更新系统时间的更多相关文章
- Linux命令-更新系统时间和硬件时间
查看系统时间和时区: date 查看系统时间date -R 查看时区 修改时区: tzselect 修改时区 或 cp /usr/share/zoneinfo/Asia/Shanghai /etc/l ...
- ntpdate更新系统时间时报错Can't find host ntp1.aliyun.com: Servname not supported for ai_socktype (-8)
ntpdate更新系统时间时报错Can't find host ntp1.aliyun.com: Servname not supported for ai_socktype (-8) 所报错误: [ ...
- CentOS 7更新系统时间
Linux系统在安装的时候,总是会出现时区,时间的错误. 将Linux系统时间和本地区网络时间同步,ntpdate可以从网络同步时间, 需要安装sudo yum install ntp ntpdate ...
- 更新系统时间 & 查看/修改LINUX时区和时间
一.时区0. date '+%Y%M%D' 按照格式显示当前日期,结果如下: date "+%Y-%m-%d %H:%M:%S" 1. 查看当前时区 :[root@master ~ ...
- 同步linux系统时间
Linux的时间分为System Clock(系统时间)和Real Time Clock (硬件时间,简称RTC). 系统时间:指当前Linux Kernel中的时间. 硬件时间:主板上有电池供电的时 ...
- linux更新系统时间
查看时间 date 更新时间 yum install ntpdate ntpdate time.windows.com
- Linux命令更新系统时间,更新所有文件的时间(转)
https://blog.csdn.net/ccj2020/article/details/76026606
- bat 同步windows系统时间
需要使用管理员权限运行 net start w32timew32tm /config /updatew32tm /resync /rediscovernet stop w32timepause
- Cef 因系统时间不正常,导致页面访问空白问题
当我们的系统时间不正常,比如设置一个日期-1999年9月9日,会引发证书问题. 系统时间不正常-IE有概率能访问 触发NavigateError事件,异常代码INET_E_INVALID_CERTIF ...
随机推荐
- 推荐系统:MovivLens20M数据集解析
MovieLens 是历史最悠久的推荐系统.它由美国 Minnesota 大学计算机科学与工程学院的 GroupLens 项目组创办,是一个非商业性质的.以研究为目的的实验性站点.MovieLens ...
- [实战经验][SQL Sever 2008 (R)解决方法累积
SQL Sever 2008 (R)的安装图解及配置 http://www.soft6.com/v9/2009/jcsj_1030/115821.html 产品密钥,选择“输入产品密钥”,输入:PTT ...
- java StringUtils
/** * */ package com.sign.utils; import java.util.regex.Pattern; /** * @author Administrator * creat ...
- Qt中采用多线程实现Socket编程
Socket通常也称作"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求. 本文介绍的是Qt中采用多线程Socket编程,由于工作的需要,开始 ...
- 修复Thinkphp框架5.0和5.1版本的远程代码执行安全漏洞
由于框架对控制器名没有进行足够的检测会导致在没有开启强制路由的情况下可能的getshell漏洞.最直接的影响为index.php直接被篡改成首页html的内容! 5.0版本 thinkphp/libr ...
- Full-featured Vue 评分组件
分享一下最近写的 vue 的评分组件 Features: 支持半星.可清除.文案展示.只读.自定义颜色.自定义字符及图片等.支持 hover 的时候改变 value.内置三种样式,以及非常好看 DEM ...
- Problem 16
Problem 16 pow(2, 15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.2的15次方等于32768,而这些数 ...
- 【Zoj 4061】Magic Multiplication
[链接] 我是链接,点我呀:) [题意] [题解] /* for a[1] from 1~9 1*1=1 2*1=2 3*1=3 1*2=2 2*2=4 3*2=6 1*3=3 2*3=6 3*3=9 ...
- oracle到mysql的导数据方式(适用于任意数据源之间的互导)
http://www.wfuyu.com/Internet/19955.html 为了生产库释放部份资源, 需要将API模块迁移到mysql中,及需要导数据. 尝试了oracle to mysql工具 ...
- windows终端 进入文件夹
盘符: 例如想进入D盘 d: cd 进入到当前盘某个目录.cd \ 进入当前盘根目录cd \windows 进入到当前盘Windows目录cd.. 退出到上一级目录 注:进入含有特殊字符目录时需要加引 ...