日期计算代码(1):计算当前时间前后N天

C语言计算当前时间前后N天可以借助库函数<time.h>提供的函数,先获取当前时间从1970年开始累计的秒数,再加减N天对应的秒数,最后将秒数还原年月日时间,具体代码如下。

 
 
  1. #inlcude  <time.h>
  2.  
  3. int main(int argc, char* argv[])
  4. {
  5. time_t lt;
  6. lt = time(NULL);
  7.  
  8. long seconds = 24 * 3600 * 20;//24 小时 * 小时秒 * 天数
  9. lt += seconds;//计算后N天
  10. //lt -= seconds;//计算前N天
  11.  
  12. struct tm *p = localtime(&lt);
  13. printf("时间为:%d年%d月%d日%d时%d分%d秒n",
  14. p->tm_year + 1900,
  15. p->tm_mon + 1,
  16. p->tm_mday,
  17. p->tm_hour,
  18. p->tm_min,
  19. p->tm_sec);
  20. }

 说明:

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结构如下:

 
 
  1. struct tm {
  2. int tm_sec; /* seconds after the minute - [0,59] */
  3. int tm_min; /* minutes after the hour - [0,59] */
  4. int tm_hour; /* hours since midnight - [0,23] */
  5. int tm_mday; /* day of the month - [1,31] */
  6. int tm_mon; /* months since January - [0,11] */
  7. int tm_year; /* years since 1900 */
  8. int tm_wday; /* days since Sunday - [0,6] */
  9. int tm_yday; /* days since January 1 - [0,365] */
  10. int tm_isdst; /* 是否夏令时(中国大陆不实行夏令时间) */
  11. };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值