实验2 :100天后的时间
输出当前时间
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TIMESTRSIZE 1024
int main()
{
time_t stamp;
struct tm *tm;
char timestr[TIMESTRSIZE];
// 获取内核时间,即 time_t 格式时间
stamp = time(NULL);
//将 time_t 格式时间 装换为 tm 格式时间,即将 内核 秒单位时间 转为 程序员结构体格式时间
tm = localtime(&stamp);
//将程序员喜欢用的 tm 结构体格式时间 转换为 普通用户喜欢的字符串格式时间
strftime(timestr,TIMESTRSIZE,"Now:%Y-%m-%d",tm);
//打印字符串格式时间
puts(timestr);
exit(0);
}
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$ gcc 100.c
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$ ./a.out
Now:2020-05-10
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$
100天后时间:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define TIMESTRSIZE 1024
int main()
{
time_t stamp;
struct tm *tm;
char timestr[TIMESTRSIZE];
stamp = time(NULL);
tm = localtime(&stamp);
strftime(timestr,TIMESTRSIZE,"100 days later:%Y-%m-%d",tm);
puts(timestr);
//直接将 tm 格式中的 天 时间信息 加100,暂时不用担心 溢出
tm->tm_mday += 100;
// 这里是重点,利用 mktime()会修正 tm 格式时间,并转为time_t格式时间的特性,修正tm 格式时间
mktime(tm);
strftime(timestr,TIMESTRSIZE,"Now:%Y-%m-%d",tm);
puts(timestr);
exit(0);
}
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$ gcc 100.c
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$ ./a.out
100 days later:2020-05-10
Now:2020-08-18
mhr@ubuntu:~/work/linux/muluheyonghucaozuo/30$