最近业务需要计算某个时间点距离1970年1月1日的秒数,以下是两种实现:
第一种:
#define is_leap_year(y) (((y) % 4 == 0 && (y) % 100 != 0) || (y) % 400 == 0) /* 计算某个日期距1970年1月1日0时0分0秒的秒数 */ time_t calSecSince1970(int Y, int M, int D, int h, int m, int s) { int i = 0; int sec = 0; int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /* 年计算 */ for(i = 1970; i < Y; i++) { if(is_leap_year(i)) sec += 366 * 24 * 60 * 60; else sec += 365 * 24 * 60 * 60; } /* 月计算 */ for(i = 1; i < M; i++) { sec += days[i] * 24 * 60 * 60; if(i == 2 && is_leap_year(Y)) { sec += 24 * 60 * 60; } } /* 天计算 */ sec += (D - 1) * 24 * 60 * 60; /* 时分秒计算 */ sec += h * 60 * 60 + m * 60 + s; return sec; }
第二种
linux源码实现,只能说流批,有兴趣的小伙伴可以研究下:
unsigned long mktime (unsigned int year, unsigned int mon, 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 */ }