1、localtime函数:
原型:struct tm * localtime(const time_t * clock);
功能:把从1970-1-1零点零分到当前时间系统所偏移的秒数时间转换为本地时间, 其中clock为秒数时间;
返回值:返回一个tm结构体的指针。tm结构体是time.h中定义的用于分别存储时间的各个量(年月日等)的结构体。
2、asctime函数:
原型:char* asctime (const struct tm * timeptr);
功能:把timeptr指向的tm结构体中储存的时间转换为字符串;
返回值:一个固定格式的字符串。字符串格式为:Www Mmm dd hh:mm:ss yyyy。其中Www为星期,Mmm为月份,dd为日,hh为时,mm为分,ss为秒,yyyy为年份;
3、例程:
#include<time.h> #include<stdio.h> int main(){ time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime);//使用localtime函数把秒数时间rawtime转换为本地时间以tm结构体保存,并把tm结构体地址储存到timeinfo当中 printf("当前日期为: %s",asctime(timeinfo));//使用asctime函数把tm结构体中储存的时间转换为字符串,并输出 return 0;}
#include <stdio.h> #include <time.h> #define TIME_MAX 32 void get_time(void); int main() { get_time(); getchar(); return 0; } void get_time(void) { time_t now; time(&now); // 定义两个变量,存储转换结果 struct tm tmTmp; char stTmp[TIME_MAX]; // 转换为tm结构 localtime_s(&tmTmp,&now); // 转换为字符串并输出 asctime_s(stTmp,&tmTmp); printf("Current time is: %s\n",stTmp); }