您的位置:首页 > 运维架构 > Linux

Linux下获得系统时间的C语言的实现方法[转]

2008-09-18 21:35 1221 查看
转自:
http://www.icgle.net/Technic/technic/2007/5/29/Technic11603.htm
#include<time.h> //C语言的头文件

#include<stdio.h> //C语言的I/O

void main()

{

time_t now; //实例化time_t结构

struct tm *timenow; //实例化tm结构指针

time(&now);

//time函数读取现在的时间(国际标准时间非北京时间),然后传值给now

timenow = localtime(&now);

//localtime函数把从time取得的时间now换算成你电脑中的时间(就是你设置的地区)

printf("Local time is %s/n",asctime(timenow));

//上句中asctime函数把时间转换成字符,通过printf()函数输出

}

注释:time_t是一个在time.h中定义好的结构体。而tm结构体的原形如下:

struct tm

{

int tm_sec;//seconds 0-61

int tm_min;//minutes 1-59

int tm_hour;//hours 0-23

int tm_mday;//day of the month 1-31

int tm_mon;//months since jan 0-11

int tm_year;//years from 1900

int tm_wday;//days since Sunday, 0-6

int tm_yday;//days since Jan 1, 0-365

int tm_isdst;//Daylight Saving time indicator

};

#include "time.h"

time_t time(time_t *timer);

调用后将当前系统时间与1900年1月1日相差的秒数存入到timer中,timer可看成是一个长整型数

struct tm* localtime(const time_t *timer)

将time()函数调用的结果做为参数传入到localtime()函数中就能得到当前时间和日期,注意得到的年是和1970的差值,月份是和1月的差值

struct tm是一个结构体,定义如下

struct tm

{

int tm_sec; //当前秒

int tm_min; //当前分钟

int tm_hour; //当前小时

int tm_mday; //当前在本月中的天,如11月1日,则为1

int tm_mon; //当前月,范围是0~11

int tm_year; //当前年和1900的差值,如2006年则为36

int tm_wday; //当前在本星期中的天,范围0~6

int tm_yday; //当前在本年中的天,范围0~365

int tm_isdst; //这个我也不清楚

}

求当前时间的示例

int getSystemTime()

{

time_t timer;

struct tm* t_tm;

time(&timer);

t_tm = localtime(&timer);

printf("today is %4d%02d%02d%02d%02d%02d/n", t_tm.tm_year+1900,

t_tm.tm_mon+1, t_tm.tm_mday, t_tm.tm_hour, t_tm.tm_min, t_tm.tm_sec);

return 0;

}

其他时间的函数和结构还有:

timeval结构

#include <include/linux/time.h>

struct timeval

{

time_t tv_sec;

susecond_t tv_usec; //当前妙内的微妙数

};

tms结构

保存着一个进程及其子进程使用的cpu时间

struct tms

{

clock_t tms_utime;

clock_t tms_stime;

clock_t tms_cutime;

clock_t tms_cstime;

}

timer_struct结构

#include <include/linux/timer.h>

struct timer_struct

{

unsigned long expires; //定时器被激活的时刻

void (*fn)(void); //定时器激活后的处理函数

}

utime函数

更改文件的存取和修改时间

int utime(const char pathname, const struct utimbuf *times) // return value 0 or -1

times 为空指针,存取和修改时间设置为当前时间

struct utimbuf

{

time_t actime;

time_t modtime;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: