源代码
包含两个文件:
get_internet_time.h
get_internet_time.cpp
点击这里下载
使用方法
#include "get_internet_time.h"
using namespace std;
/*
Name: demo
Function: a demo shows how to use this API to get internet time
params: None
return: None
Author: Leo Ma
Date: 2019.09.17
*/
//just rename this function to main(),and test this API
int main()
{
struct tm *tim = new struct tm;
time_t timeRecv1, timeRecv2;
if(!get_internet_time(&timeRecv1)) cout<<"get internet time successfully!" <<endl;//成功获取时间,返回0
tim = localtime(&timeRecv1);//这个函数返回了一个指向struct tm类型的地址
tim->tm_year += 1900;
tim->tm_mon += 1;
printf("%lld -> %d-%02d-%02d %02d:%02d:%02d\r\n",timeRecv1, tim->tm_year, tim->tm_mon, tim->tm_mday, tim->tm_hour, tim->tm_min, tim->tm_sec);
cout << "wating for a while..." << endl;
Sleep(20*1000);//20s
if (!get_internet_time(&timeRecv2)) cout << "get internet time successfully!" << endl;//成功获取时间,返回0
tim = localtime(&timeRecv2);//这个函数返回了一个指向struct tm类型的地址
tim->tm_year += 1900;
tim->tm_mon += 1;
printf("%lld -> %d-%02d-%02d %02d:%02d:%02d\r\n", timeRecv1, tim->tm_year, tim->tm_mon, tim->tm_mday, tim->tm_hour, tim->tm_min, tim->tm_sec);
//计算时间差
double cost;
cost = difftime(timeRecv2, timeRecv1);//返回的时间差单位是秒
cout << "cost " << cost << "s" << endl;
system("pause");
return 0;
}
运行结果:

本文介绍了一种使用C++从NTP服务器获取网络时间的方法,通过提供的源代码示例,展示了如何实现网络时间同步,包括获取时间、显示时间和计算时间差。
3840

被折叠的 条评论
为什么被折叠?



