给出两个时间点,计算它们之间相差的时间间隔:
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string>
using namespace std;
int standard_to_stamp(char *str_time)
{
struct tm stm;
int iY, iM, iD, iH, iMin, iS;
memset(&stm,0,sizeof(stm));
iY = atoi(str_time);
iM = atoi(str_time+5);
iD = atoi(str_time+8);
iH = atoi(str_time+11);
iMin = atoi(str_time+14);
iS = atoi(str_time+17);
stm.tm_year=iY-1900;
stm.tm_mon=iM-1;
stm.tm_mday=iD;
stm.tm_hour=iH;
stm.tm_min=iMin;
stm.tm_sec=iS;
return (int)mktime(&stm);
}
string num_to_str(int i)
{
stringstream ss;
ss << i;
return ss.str();
}
void time_diff(char *str_time1, char *str_time2)
{
int time1 = standard_to_stamp(str_time1);
int time2 = standard_to_stamp(str_time2);
int diff = time2 - time1;
int hour = diff / 3600;
int minute = diff / 60 % 60;
int second = diff % 60;
string descStr = "两个时间段相差为:";
std::string timestr = "";
if (hour > 0)
{
timestr += num_to_str(hour);
timestr += "小时";
}
if (minute > 0)
{
timestr += num_to_str(minute);
timestr += "分钟";
}
if (second > 0)
{
timestr += num_to_str(second);
timestr += "秒";
}
cout << descStr + timestr << endl;
}
int main()
{
time_diff("2017:07:06 15:20:00", "2017:07:06 21:50:55");
return 0;
}
运行结果如下: