一、说明: Linux内部对时间是用从Epoch时间开始计时的秒数来表示的。Epoch也就是通用协调时间(UTC,也就是格林尼治平均时间或格林威治标准时间,CMT)。Linux将这个数据存储在time_t结构体变量里。
二、用到的函数:time()&localtime()函数
1. time() 函数
/* time - 获取计算机系统当前的日历时间(Calender Time)
* 处理日期时间的函数都是以本函数的返回值为基础进行运算
*
* 函数原型:
* #include <time.h>
*
* time_t time(time_t *calptr);
*
* 返回值:
* 成功:秒数,从1970-1-1,00:00:00
*
* 使用:
* time_t now;
*
* time(&now); // == now = time(NULL);
*/
2. localtime() 函数
/*
* localtime - 将时间数值变换成本地时间,考虑到本地时区和夏令时标志
*
* 函数声明:
* #include <time.h>
*
* struct tm * localtime(const time_t *timer);
*
*/
/* 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到11 */
int tm_year; /*自 1900起的年数 */
int tm_wday; /*一周中的第几天,范围从0到6 */
int tm_yday; /*一年中的第几天,范围从0到365 */
int tm_isdst; /*夏令时 */
};
3、编程:
main.c文件
// 测试代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /*related to tm struct */
#include <sys/time.h>
#include <string.h>
int main()
{
time_t current_time;
struct tm *current;
char time_data[32] = "";
char *ptr = NULL;//avoid Null pointer
ptr = time_data;
time(¤t_time);
current = localtime(¤t_time);
//时间转换
sprintf(time_data,"%04d-%02d-%02d-%02d:02%d:%02d",current->tm_year+1900,current->tm_mon+1,current->tm_mday,current->tm_hour,current->tm_min,current->tm_sec);
printf("Current time is:%s",ptr+1);
return 0;
}
生成time.c模块,方便调用:
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /*related to tm struct */
#include <sys/time.h>
#include <string.h>
/*get time*/
char *get_current_time()//返回指针
{
time_t current_time;
struct tm *current;
char time_data[32] = "";
char *ptr = NULL;//avoid Null pointer
ptr = time_data;
time(¤t_time);
current = localtime(¤t_time);
sprintf(time_data,"%d-%d-%d-%d:%d:%d",current->tm_year+1900,current->tm_mon+1,current->tm_mday,current->tm_hour,current->tm_min,current->tm_sec);
return (strcpy(ptr,time_data));
}