转载地址:https://www.eefocus.com/xuefu2009/blog/10-04/188676_67757.html
(1)time_t整数转日期时间
#include <stdio.h>
#include <time.h>
int main()
{
char *wday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};/*指针字符数组*/
time_t t;
struct tm *p;
t=time(NULL);/*获取从1970年1月1日零时到现在的秒数,保存到变量t中*/
p=gmtime(&t); /*变量t的值转换为实际日期时间的表示格式*/
printf("%d年%02d月%02d日",(1900+p->tm_year), (1+p->tm_mon),p->tm_mday);
printf(" %s ", wday[p->tm_wday]);
printf("%02d:%02d:%02d\n", p->tm_hour, p->tm_min, p->tm_sec);
return 0;
}
注意:p=gmtime(&t);此行若改为p=localtime(&t);则返回当前时区的时间
(2)日期时间转time_t整数
#include <stdio.h>
#include <time.h>
int main()
{
time_t t;
struct tm stm;
printf("请输入日期时间值(按yyyy/mm/dd hh:mm:ss格式):");
scanf("%d/%d/%d %d:%d:%d",&stm.tm_year,&stm.tm_mon,&stm.tm_mday,
&stm.tm_hour,&stm.tm_min,&stm.tm_sec);
stm.tm_year-=1900; /*年份值减去1900,得到tm结构中保存的年份序数*/
stm.tm_mon-=1; /*月份值减去1,得到tm结构中保存的月份序数*/
t=mktime(&stm); /* 若用户输入的日期时间有误,则函数返回值为-1*/
if(-1==t)
{
printf("输入的日期时间格式出错!\n");
exit(1);
}
printf("1970/01/01 00:00:00~%d/%02d/%02d %02d:%02d:%02d共%d秒\n",
stm.tm_year+1900,stm.tm_mon,stm.tm_mday,
stm.tm_hour,stm.tm_min,stm.tm_sec,t);
return 0;
}