C语言计算当前时间前后N天可以借助库函数<time.h>提供的函数,先获取当前时间从1970年开始累计的秒数,再加减N天对应的秒数,最后将秒数还原年月日时间,具体代码如下。
- #inlcude <time.h>
- int main(int argc, char* argv[])
- {
- time_t lt;
- lt = time(NULL);
- long seconds = 24 * 3600 * 20;//24 小时 * 小时秒 * 天数
- lt += seconds;//计算后N天
- //lt -= seconds;//计算前N天
- struct tm *p = localtime(<);
- printf("时间为:%d年%d月%d日%d时%d分%d秒n",
- p->tm_year + 1900,
- p->tm_mon + 1,
- p->tm_mday,
- p->tm_hour,
- p->tm_min,
- p->tm_sec);
- }
说明:
time(NULL):返回从1970年1月1日0时0分0秒到当前时间所偏移的秒数。
localtime():将从1970年1月1日0时0分0秒到当前时间所偏移的秒数,转化成本地时间年月日时分秒。
该方法不能计算1970年以前的时间,由于time_t数据类型(即long 类型)能表示的数值范围有限,超出time_t的最大值之后的时间将无法表示。32位平台可以表示的时间不能晚于2038年1月18日19时14分07秒,64位平台能表示的最大时间为3001年1月1日0时0分0秒(不包括该时间点)。
struct tm结构如下:
- struct tm {
- int tm_sec; /* seconds after the minute - [0,59] */
- int tm_min; /* minutes after the hour - [0,59] */
- int tm_hour; /* hours since midnight - [0,23] */
- int tm_mday; /* day of the month - [1,31] */
- int tm_mon; /* months since January - [0,11] */
- int tm_year; /* years since 1900 */
- int tm_wday; /* days since Sunday - [0,6] */
- int tm_yday; /* days since January 1 - [0,365] */
- int tm_isdst; /* 是否夏令时(中国大陆不实行夏令时间) */
- };