时间相关编程

timeval

timeval结构可以用来保存时间信息。

在文件<sys/time.h>中定义,结构如下:

struct timeval {
    time_t tv_sec; /* seconds */
    suseconds_t tv_usec; /* microseconds */
};

其中tv_usec为微秒(10-6秒) 。

 

其主要用法如下:

struct timeval e;
gettimeofday(&e, NULL);//获得当前时间
settimeofday(&e, NULL);//设置当前时间

time_t

time_t保存时间信息,其实际为一个长整型。是用“从一个标准时间点到此时的时间经过的秒数”来表示的时间。

常用方法

1.基本用法

#include <time.h>
#include <stdio.h>
#include <dos.h>
int main(void)
{
  time_t t;
    t = time(NULL);
  printf("The number of seconds since January 1, 1970 is %ld",t);
  return 0;
}

2.time函数也常用于随机数的生成,用日历时间作为种子。

#include <stdio.h> 
#include <time.h> 
#include<stdlib.h> 

int main(void) 
{ 
  int i; 
  srand((unsigned) time(NULL)); 
  printf("ten random numbers from 0 to 99\n\n"); 
  for(i=0;i<10;i++) 
  { 
    printf("%d\n",rand()%100); 
  } 
  return 0; 
} 

3.用time()函数结合其他函数(如:localtime、gmtimeasctimectime)可以获得当前系统时间或是标准时间。

#include <stdio.h> 
#include <stddef.h> 
#include <time.h> 

int main(void) 
{ 
  time_t timer;//time_t就是long int 类型 
  struct tm *tblock; 
  timer = time(NULL);//这一句也可以改成time(&timer); 
  tblock = localtime(&timer); 
  printf("Local time is: %s\n",asctime(tblock)); 
  return 0; 
}

struct tm

 

struct tm 
{ 
    int tm_sec;        //目前秒数,正常范围为0-59,但允许至61秒 
     int tm_min;        //目前分数,范围0-59 
    int tm_hour;       //午夜算起的时数,范围为0-23 
    int tm_mday;       //目前月份的日数,范围01-31 
    int tm_mon;        //目前月份,从一月算起,范围从0-11 
    int tm_year;       //从1900 年算起至今的年数 
     int tm_wday;       //一星期的日数,从星期一算起,范围为1-7 
    int tm_yday;      //从今年1月1日算起至今的天数,范围为0-365 
    int tm_isdst;     //夏令时标识符,实行夏令时的时候,tm_isdst为正。
                         //不实行夏令时的进候,tm_isdst为0;
                         //不了解情况时,tm_isdst为负。
}; 
 

函数

gmtime

truct tm*gmtime(const time_t*timep); 
函数说明
gmtime()将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm返回。
 
示例: 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(int argc, char* argv[])
{
    time_t cur_time;
    struct tm* tm_time;

    cur_time = time(NULL);
    printf("the number of seconds since 1970.1.1 is %ld\n", cur_time);
    
    //UTC时间
    tm_time = gmtime(&cur_time);
    printf("%d-%d-%d\n",(1900+tm_time->tm_year), (1+tm_time->tm_mon),tm_time->tm_mday); 
    printf("%d %d:%d:%d\n", tm_time->tm_wday, tm_time->tm_hour, tm_time->tm_min, tm_time->tm_sec); 

    return 0;
}
 

localtime

struct tm *localtime(const time_t * timep); 
函数说明:取得当地目前时间和日期
示例:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main(int argc, char* argv[])
{
    time_t cur_time;
    struct tm* tm_time;

    cur_time = time(NULL);
    printf("the number of seconds since 1970.1.1 is %ld\n", cur_time);

    tm_time = localtime(&cur_time);
    printf("%d-%d-%d\n",(1900+tm_time->tm_year), (1+tm_time->tm_mon),tm_time->tm_mday); 
    printf("%d %d:%d:%d\n", tm_time->tm_wday, 
            tm_time->tm_hour, tm_time->tm_min, tm_time->tm_sec); 
    return 0;
}

posted on 2010-09-19 17:54  谷底望月  阅读(293)  评论(0编辑  收藏  举报

导航