码迷,mamicode.com
首页 > 其他好文 > 详细

获取两个字符串日期的差值的方法

时间:2015-10-24 10:08:52      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:

日期的格式:“yymmddhhmmss”是一个字符串,计算两个日期之间的差值,显然就是计算两个日期之间相差的秒数,有个简洁的方法是将字符串转化为time_t格式,用time_t表示的时间(日历时间)是从一个时间点(例如:1970年1月1日0时0分0秒)到此时的秒数

我们可以看到它的定义是这样的

#ifndef _TIME_T_DEFINED
typedef long time_t;           /* 时间值 */
#define _TIME_T_DEFINED       /* 避免重复定义 time_t */
#endif

由于长整形数值大小的限制,它所表示的时间不能晚于2038年1月18日19时14分07秒,所以现在我们还能放心的使用二十多年。

转化成整数之后,求取差值即可

我当初没有想到此方法,用了一种比较笨的办法,就是计算:相差天数*1440*60+相差秒数

代码大概是这样的:

//获取两个时间相差分钟数
int GetDifMin(string strTime1, string strTime2)
{
	if (strTime1.length() != 12 || strTime2.length() != 12)
	{
		return -1;
	}
	if (strTime1.compare(strTime2) < 0)
	{
		string linshi = strTime1;
		strTime1 = strTime2;
		strTime2 = linshi;
	}

	int iDefDays = 0;
	if (strcmp(strTime1.substr(0, 8).c_str(), strTime2.substr(0, 8).c_str()) > 0)
	{
		int iDaysCount1 = 0;
		int iDaysCount2 = 0;
		int iYear1, iYear2, iMonth1, iMonth2, iDay1, iDay2;
		iYear1 = iYear2 = iMonth1 = iMonth2 = iDay1 = iDay2 = 0;
		iYear1 = atoi(strTime1.substr(0, 4).c_str());
		iYear2 = atoi(strTime2.substr(0, 4).c_str());
		iMonth1 = atoi(strTime1.substr(4, 2).c_str());
		iMonth2 = atoi(strTime2.substr(4, 2).c_str());
		iDay1 = atoi(strTime1.substr(6, 2).c_str());
		iDay2 = atoi(strTime2.substr(6, 2).c_str());
		int DAY[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		if ((iYear1 % 4 == 0 || iYear1 % 400 == 0) && (iYear1 % 100 != 0))
		{
			DAY[1] = 29;
		}
		for (int i = 0; i < iMonth1 - 1; i++)
		{
			iDaysCount1 += DAY[i];
		}
		iDaysCount1 += iDay1;

		DAY[1] = 28;
		if ((iYear2 % 4 == 0 || iYear2 % 400 == 0) && (iYear2 % 100 != 0))
		{
			DAY[1] = 29;
		}
		for (int i = 0; i < iMonth2 - 1; i++)
		{
			iDaysCount2 += DAY[i];
		}
		iDaysCount2 += iDay2;

		if (iYear1 > iYear2)
		{
			for (int i = iYear2; i < iYear1; i++)
			{
				iDaysCount1 += 365;
				if ((i % 4 == 0 || i % 400 == 0) && (i % 100 != 0))
				{
					iDaysCount1++;
				}
			}
		}
		iDefDays = iDaysCount1 - iDaysCount2;
	}
	int ret = iDefDays * 1440;
	string hour1 = strTime1.substr(8, 2);
	string hour2 = strTime2.substr(8, 2);
	ret += (atoi(hour1.c_str()) - atoi(hour2.c_str())) * 60;
	string min1 = strTime1.substr(10, 2);
	string min2 = strTime2.substr(10, 2);
	ret += atoi(min1.c_str()) - atoi(min2.c_str());
	return ret;
}

  此函数的日期格式与上面讲到的相似,只是没有秒数,其他的都是相同的。

获取两个字符串日期的差值的方法

标签:

原文地址:http://www.cnblogs.com/yunbuyi/p/4906222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!