本篇介绍一些关于C++语言的时间计算的函数如时间戳、当前时间、当前本地时间、时区时间、时间差以及时间的字符串字符串格式化等。
/*
* Author:W;
* 时间函数
*/
//引入头文件:头文件包含了程序中必需的或有用的信息【单行注释】
#include <iostream>
//引入时间函数库
#include <time.h>
#include <Windows.h>
//命名空间使用
using namespace std;
//伦敦时时区
#define BST (+1)
//北京时区
#define CCT (+8)
//main程序执行入口函数
int main()
{
//1.时间戳
time_t seconds = time(NULL);
cout<<"====时间戳===="<< endl;
cout << "自Epoch(1970-01-01 00:00:00 UTC)起经过的时间,以秒为单位 seconds = " << seconds << endl;
//2.时间字符串
cout << "====时间字符串====" << endl;
time_t curTime;
time(&curTime);
size_t size = 100;
char buffer[100];
ctime_s(buffer, size, &curTime);
cout << "当前时间的字符串格式:" << buffer << endl;
//3.本地时间
cout << "====本地时间字符串格式====="<< endl;
time_t curLocalTime;
time(&curLocalTime);
struct tm info;
localtime_s(&info,&curLocalTime);
char buffer2[80];
strftime(buffer2, 80, "%Y-%m-%d %H:%M:%S", &info);
cout << "当前本地时间特定时间格式显示:"<< buffer2 << endl;
asctime_s(buffer2, &info);
cout << "当前本地时间字符串格式:" << buffer2 << endl;
//4.世界时区
cout << "====世界各地时区计算=====" << endl;
time_t curZonetime;
struct tm info2;
time(&curZonetime);
/* 获取 GMT 时间 */
gmtime_s(&info2,&curZonetime);
printf("伦敦:%2d:%02d\n", (info2.tm_hour + BST) % 24, info2.tm_min);
printf("中国:%2d:%02d\n", (info2.tm_hour + CCT) % 24, info2.tm_min);
//5.时间差
cout << "====时间差=====" << endl;
time_t startTime;
time(&startTime);
Sleep(5000);
time_t endTime;
time(&endTime);
cout << "开始时间:"<< startTime;
cout << " 结束时间:"<< endTime;
cout << " 时间差:"<<difftime(endTime, startTime) << endl;
}
运行结果如下: