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 ...
随机推荐
- C# 查找、结束进程 - 通过进程名精确、模糊查找、结束进程
/// <summary> /// 根据“精确进程名”结束进程 /// </summary> /// <param name="strProcName" ...
- sql server 游标fetch简单用法
//遍历tmp_check的年份和月份 DECLARE @year ) DECLARE @month ) DECLARE cur CURSOR FOR SELECT nf,yf FROM tmp_ch ...
- SLAM: Ubuntu14.04_Kylin安装ROS-Indigo
参考连接:ROS-Indigo版在Ubuntu上的安装第一步: 软件源配置 1. 增加下载源(增加ubuntu版的ros数据仓库,即下载源)(通用指令适合任何版本的ros) sudo sh -c 'e ...
- nginx_安装测试
首先安装环境: [root@local nginx-1.9.14]# yum install gcc-c++ pcre pcre-devel zlib zlib-devel openssl op ...
- 【转载】java 监听文件或者文件夹变化的几种方式
1.log4j的实现的文件内容变化监听 package com.jp.filemonitor; import org.apache.log4j.helpers.FileWatchdog; public ...
- java环境搭建心得
右击此电脑,点击属性, 在打开的电脑系统对话框里发电机i直接点击左侧导航里的[高级系统设置]在打开的电脑系统属性对话框里直接点击下面的[环境变量] 打开环境变量对话框后,直接点击系统变量下面的新建, ...
- Ubuntu Server下docker实战 02: docker进阶配置
在上一篇文章里<Ubuntu Server下docker实战 01: 安装docker>,我们已经把docker安装起来了,并运行了一个hello-world 这一篇,我们继续讲进阶配置. ...
- 利用python暴力破解压缩文件密码
import randomimport sysimport zipfileimport timefrom threading import Threadfrom multiprocessing imp ...
- 如何使用qtp12 utf进行功能测试
首先,按照本博客的安装教程走的,右键管理员运行 接下来点击继续,这个界面只需要勾选到web即可 点击ok,开始运行 进入到主界面之后,file新建一个测试. 可以修改路径等等 点击create之后,出 ...
- jQuery Webcam Plugin jscam.swf文件反编译工具使用说明
jQuery webcam plugin是一个在ie,firefox,chrome下都可以用的摄像头摄像及拍照用的插件. (http://www.xarg.org/project/jquery-web ...