我们知道,从CMOS中读出来的系统时间并不是time_t类型,而是类似于struct tm那样,年月日时分秒是分开存储的。
那么,要把它转化为系统便于处理的time_t类型,就需要算法进行转换。
我们都知道我们的公历还是比较复杂的,有大月小月,有闰年非闰年,处理起来会很麻烦。
但是Linux的源代码仅仅用了短短的几行就完成了这个复杂的转换(Gauss算法),实在令人惊奇。话不多说,先看源代码:
include/linux/time.h
unsigned int day, unsigned int hour,
unsigned int min, unsigned int sec)
... {
if (0 >= (int) (mon -= 2)) ...{ /**//* 1..12 -> 11,12,1..10 */
mon += 12; /**//* Puts Feb last since it has leap day */
year -= 1;
}
return (((
(unsigned long) (year/4 - year/100 + year/400 + 367*mon/12 + day) +
year*365 - 719499
)*24 + hour /**//* now have hours */
)*60 + min /**//* now have minutes */
)*60 + sec; /**//* finally seconds */
}
看上去令人眼花缭乱,毫无头绪。详情请阅读原文:http://blog.csdn.net/axx1611/article/details/1792827
应用:
/*功能: 返回YYYYMMDDHHMMSS格式的时间(sTime + sec);
*char[] sTime: YYYYMMDDHHMMSS
*int sec: 秒数 (sec 可以是负数)
*/
int StrTimeAddSec(char *sTime, int sec)
{
struct tm *pTime = new struct tm;
struct tm *pTime2;
time_t th;
pTime->tm_sec = atoi(sTime + 12) + sec;//秒
sTime[12] = '\0';
pTime->tm_min = atoi(sTime + 10);//分
sTime[10] = '\0';
pTime->tm_hour = atoi(sTime + 8);//小时
sTime[8] = '\0';
pTime->tm_mday = atoi(sTime + 6);//日
sTime[6] = '\0';
pTime->tm_mon = atoi(sTime + 4) - 1;//月份
sTime[4] = '\0';
pTime->tm_year = atoi(sTime) - 1900;//年
//th = mktime(pTime) + sec;
mktime(pTime);//自动调整时间
//pTime2 = localtime(&th);
//memset(sTime, 0, sizeof(sTime));
sprintf(sTime, "%04d%02d%02d%02d%02d%02d", pTime->tm_year + 1900, pTime->tm_mon + 1, pTime->tm_mday, pTime->tm_hour, pTime->tm_min, pTime->tm_sec);
//delete pTime2;//不用delete,因为localtime的返回值是个static的地址
delete pTime;
return 0;
}