C++獲取NTP服務器上的網絡時間

C++獲取NTP服務器上的網絡時間

源代碼

包含兩個文件:
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;
}

運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章