同步服务器时间到机台系统时间

#一、功能需求说明
通过服务器发来的时间(字符串格式),来更新机台系统时间,机台与服务器之间的通讯采用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;
}

注: 此文是本人原创,转载请声明。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值