#一、功能需求说明
通过服务器发来的时间(字符串格式),来更新机台系统时间,机台与服务器之间的通讯采用TCP/IP。开发平台:VS2015 、C++。
具体代码如下:
#include "stdafx.h"
#include <WinSock2.h>
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <array>
#include <string>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main()
{
SYSTEMTIME curr_st;
GetLocalTime(&curr_st);
string times = "2022-10-10 10:00:00"; //可改为接收的服务器时间字符串
string newtimes;
std::array<int, 20> ntime{};
for (int i =0; i < times.length(); ++i)
{
if (times[i] >= '0' && times[i] <= '9')
{
newtimes += times[i];
}
}
for (int i = 0; i < newtimes.length(); ++i)
{
ntime[i] = (int)(newtimes.at(i) - 48);
}
int year, month, day, hour, minute, second;
year = ntime.at(0) * 1000 + ntime.at(1) * 100 + ntime.at(2) * 10 + ntime.at(3);
month = ntime.at(4) * 10 + ntime.at(5);
day = ntime.at(6) * 10 + ntime.at(7);
hour = ntime.at(8) * 10 + ntime.at(9);
minute = ntime.at(10) * 10 + ntime.at(11);
second = ntime.at(12) * 10 + ntime.at(13);
curr_st.wYear = year;
curr_st.wMonth = month;
curr_st.wDay = day;
curr_st.wHour = hour;
curr_st.wMinute = minute;
curr_st.wSecond = second;
curr_st.wMilliseconds = 999;
if (SetLocalTime(&curr_st))
{
printf(" 成功与时间服务器的时间同步!\n");
}
else
{
printf(" 时间服务器不能确定当前时间!\n");
system("PAUSE");
}
return 0;
}
注: 此文是本人原创,转载请声明。