1. tm结构时间和time_t时间的转换
#include <time.h>
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
using namespace std;
int main(int argc, char * argv[])
{
time_t raw_time;
struct tm *time_info;
char time_buffer[256];
raw_time = time(nullptr);
cout << "The raw_time is " << raw_time << endl;
time_info = localtime(&raw_time);
// 将时间转化为想要的数据格式
sprintf(time_buffer, "%4d_%02d_%02d_%02d_%02d_%02d", time_info->tm_year+1900, time_info->tm_mon+1, \
time_info->tm_mday, time_info->tm_hour, time_info->tm_min, time_info->tm_sec);
cout << "The time buffer is " << time_buffer << endl;
// 将时间的年月日放在向量中
vector<int> time1;
char *pch;
pch = strtok(time_buffer,"_");
while (pch != NULL){
printf ("%s\n",pch);
time1.push_back(atoi(pch));
pch = strtok(NULL, "_");
}
// for debug
/*
for (vector<int>::iterator it = time.begin(); it != time.end(); it++)
{
cout << *it << endl;
}
*/
// 将tm结构时间转化为time_t时间
cout << time1[0] << endl;
struct tm *time_info2 = NULL;
time_info2 = (struct tm*)malloc(sizeof(struct tm));
time_info2->tm_year = time1[0] - 1900;
time_info2->tm_mon = time1[1] - 1;
time_info2->tm_mday = time1[2];
time_info2->tm_hour = time1[3];
time_info2->tm_min = time1[4];
time_info2->tm_sec = time1[5];
time_info2->tm_isdst = 0; //夏令时标识符也需要赋值,否则会出错
printf( "The time is %4d_%02d_%02d_%02d_%02d_%02d\n", time_info2->tm_year+1900, time_info2->tm_mon+1, \
time_info2->tm_mday, time_info2->tm_hour, time_info2->tm_min, time_info2->tm_sec);
time_t cur_time2;
cur_time2 = mktime(time_info2);
cout << "The current time is " << cur_time2 << endl;
sleep(2);
time_t raw_time3;
raw_time3 = time(nullptr);
cout << raw_time3 << endl;
// difftime 比较两个时间相差的秒数,前面的秒数比后面大,则返回正数,否则返回负数
double seconds = difftime(raw_time3, cur_time2);
cout << "The seconds is " << seconds << endl;
free(time_info2);
}
夏令时标识符也需要赋值,否则会出错
运行结果如下:
The raw_time is 1550243429
The time buffer is 2019_02_15_23_10_29
2019
02
15
23
10
29
2019
The time is 2019_02_15_23_10_29
The current time is 1550243429
1550243431
The seconds is 2