Linux下的时间函数:获取和设置时间的函数

  /*********************************************************************************
   *      Copyright:  (C) 2016 huangan
   *                  All rights reserved.
   *
   *       Filename:  settime.c
   *    Description:  This file 
   *                 
   *        Version:  1.0.0(03/18/2016)
   *         Author:  huangan <[email protected]>
   *      ChangeLog:  1, Release initial version on "03/18/2016 03:23:45 AM"
   *                 
   ********************************************************************************/
  
  #include <stdio.h> 
  #include <time.h>
  int main(void)
  {
      time_t t1;
      time_t t2;
  
      struct tm tm;
      struct tm *ptm;
  
      ptm=&tm;
      char buf[128] = {0};

      t1 = time(&t1);
      printf("%d\n", t1);  //1355905754
      t2 = time(&t2);
      sleep(1);
      printf("%lf\n", difftime(t2, t1));  //t1,t2相差:1.000000,有时候可以用这个函数来做伪定时器
      printf("%s\n",ctime(&t1)); //Wed Dec 19 16:29:14 2012
  
      ptm->tm_year = 2012-1900;
      ptm->tm_mon = 12-1;
      ptm->tm_mday = 12;
      ptm->tm_hour = 12;
      ptm->tm_min = 12;
      ptm->tm_sec = 12;
      // 设置时间
      t1 = mktime(&tm);
       //获取时间
       ptm = localtime(&t1);
       sprintf(buf, "%04d-%02d-%02d  %02d:%02d:%02d",  ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
       printf("%s\n", buf);//2012-12-12  12:12:12
       return 0;
  }

常用时间函数如下:

time_t time(time_t *t);
char *asctime(const struct tm *tm);
char *asctime_r(const struct tm *tm, char *buf);
char *ctime(const time_t *timep);
char *ctime_r(const time_t *timep, char *buf);
struct tm *gmtime(const time_t *timep); //获取的为英国时间
struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime(const time_t *timep);      //获取的为本地时间,注意与英国时间的区别。
struct tm *localtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm);
double difftime(time_t time1, time_t time0);
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);



猜你喜欢

转载自blog.csdn.net/huangan_xixi/article/details/50950196