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

linux下c语言获取系统时间

2011-07-22 11:08 399 查看
time_t是一个大整数,表示从1970年1月1日00:00:00到当前时刻的秒数。struct tm是c/c++里的一个标准时间结构体,定义如下。

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()为负。*/
  };


下面是一个示例。

char *get_current_time()
{
//例子
static char timestr[40];
time_t t;
struct tm *nowtime;

time(&t);
nowtime = localtime(&t);
strftime(timestr,sizeof(timestr),"%Y-%m-%d %H:%M:%S",nowtime);

return timestr;
}


若想获取更高精度的时间,可以使用struct timeval,这个结构体的定义如下。

struct timeval
{
time_t tv_sec;
suseconds_t tv_usec;
};


tv_usec是一个long int数据类型,代表的是微秒(百万分之一秒)精度。

通过使用gettimeofday来获取系统时间,如下所示。

#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int main(int argc,char * argv[])
{
  struct timeval tv;
  while(1)
{
  gettimeofday(&tv,0);
  printf("time %u:%u\n",tv.tv_sec,tv.tv_usec);
  sleep(2);
  }
  return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: