需要的头文件
#include<time.h>先做一个获取系统当前时间的范例,再来解释所用的函数的作用
代码示例:
#include<stdio.h>
#include<time.h>
int main()
{
time_t timep;//定义 time_t类型变量timep,类型为long int型
time( &timep );//把获取的时间储存
//printf("%s", asctime ( localtime( &timep ) ) );
//把本地时间转化为ASCII码打印出来
return 0;
}
函数定义
char *asctime(const struct tm *timeptr)
函数说明
asctime()将参数timeptr所指的tm结构中的信息转换成真实世界所使用的时间日期表示方法,
结果以字符串形式返回 ,此函数已有时区转换为当地时间
localtime()
功 能: 把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间,
而gmtimes函数转换后的时间没有经过时区变换,是UTC时间 。
说明:此函数获得的tm结构体的时间是日历时间。
用 法: struct tm *localtime(const time_t *clock);
返回值:返回指向tm 结构体的指针.tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体.
下面写了一个详细的用localtime()和asctime()的用法的代码示例
#include<stdio.h>
#include<time.h>int main()
{
time_t timep;//定义 time_t类型变量timep ,类型为long int型
struct tm *block;
timep=time(NULL);//返回当前时间与1970年1月1日0时0分0秒相差的多少秒
printf("%ld\n",timep);
block=localtime(&timep );//把获取的时间储存
printf("%s", asctime ( block) );//把本地时间转化为ASCII码打印出来
return 0;}
结构体 struct tm是系统日历时间结构体
struct tm {
int tm_sec; /* 秒–取值区间为[0,59] */
int tm_min; /* 分 - 取值区间为[0,59] */
int tm_hour; /* 时 - 取值区间为[0,23] */
int tm_mday; /* 一个月中的日期 - 取值区间为[1,31] */
int tm_mon; /* 月份(从一月开始,0代表一月) - 取值区间为[0,11] */
int tm_year; /* 年份,其值从1900开始 */
int tm_wday; /* 星期–取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
int tm_yday; /* 从每年的1月1日开始的天数–取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
int tm_isdst; /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
long int tm_gmtoff; /*指定了日期变更线东面时区中UTC东部时区正秒数或UTC西部时区的负秒数*/
const char *tm_zone; /*当前时区的名字(与环境变量TZ有关)*/
};
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main (void)
{
struct tm *local;
time_t t;
t=time(NULL);
local=localtime(&t);
printf("local hour is :%d:%d:%d\n",local->tm_hour,local->tm_min,local->tm_sec);
printf("local hour is :%d:%d:%d\n",local->tm_mday,local->tm_mon,local->tm_year);
printf("local hour is :%d:%d:%d\n",local->tm_wday,local->tm_yday,local->tm_isdst);
printf("local hour is :%ld:%ld",local->tm_gmtoff,local->tm_zone);
return 0;
}