#include <afxsock.h>
#include <Windows.h>
#include <winsock2.h>
#pragma comment(lib, "WS2_32") // 链接到WS2_32.lib
bool NistGetTime(CTime& outtime)
{
//时间同步
CSocket sockClient;
TIME_ZONE_INFORMATION tzinfo;
DWORD dwStandardDaylight;
long bias, sminute, shour;
vector<string> vi;
string strServer;
BOOL ret;
//将时间服务器放在一个VECTOR中。
strServer = "time.nist.gov";
vi.push_back(strServer);
strServer = "time-a.nist.gov";
vi.push_back(strServer);
strServer = "time-b.nist.gov";
vi.push_back(strServer);
strServer = "time-nw.nist.gov";
vi.push_back(strServer);
strServer = "nist1.nyc.certifiedtime.com";
vi.push_back(strServer);
strServer = "time-b.nist.gov";
vi.push_back(strServer);
//初始化CSocket
AfxSocketInit();
sockClient.Create(); //创建socket
dwStandardDaylight = GetTimeZoneInformation(&tzinfo); //获取时区与UTC的时间差 应该返回-8
bias = tzinfo.Bias;
if (dwStandardDaylight == TIME_ZONE_ID_INVALID) //函数执行失败
{
return false;
}
if (dwStandardDaylight == TIME_ZONE_ID_STANDARD) //标准时间有效
bias += tzinfo.StandardBias;
if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT) //夏令时间
bias += tzinfo.DaylightBias;
shour = bias / 60;
sminute = fmod((float)bias, 60);
//循环判断服务器是否连接成功
for (int n = 0; n < vi.size(); ++n)
{
ret = sockClient.Connect(vi[n].c_str(), 13);
if (1 == ret)
break;
}
unsigned char nTime[100] = { 0 }; //临时接收数据要求足够的大
sockClient.Receive(nTime, sizeof(nTime)); //接收服务器发送来得的数据
sockClient.Close(); //关闭socket
CString strTime;
strTime.Format("%s", nTime);
if (strTime.IsEmpty())
{
return false;
}
int first = strTime.Find("-");
int second = strTime.Find("-", first + 1);
int tfirst = strTime.Find(":");
int tsecond = strTime.Find(":", tfirst + 1);
int hyear = 2000 + atoi(strTime.Mid(first - 2, 2));
int hmonth = atoi(strTime.Mid(first + 1, 2));
int hday = atoi(strTime.Mid(second + 1, 2));
int hhour = atoi(strTime.Mid(tfirst - 2, 2)) - shour;
int hminute = atoi(strTime.Mid(tfirst + 1, 2)) - sminute;
int hsecond = atoi(strTime.Mid(tsecond + 1, 2));
CTime temptime(hyear, hmonth, hday, hhour, hminute, hsecond);
outtime = temptime;
return true;
}
MFC获取网络时间
于 2023-01-10 16:55:47 首次发布