计算两个时间点间相差的时间间隔

给出两个时间点,计算它们之间相差的时间间隔:

#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;
}

运行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值