关于时间的操作

1、时间类型。

 Linux下常用的时间类型有4个:time_t,struct timeval,struct timespec,struct tm
(1)time_t是一个长整型,一般用来表示用1970年以来的秒数。
     time_t  long  integer
(2)struct timeval有两个成员,一个是秒,一个是微妙。
     struct timeval {
         long tv_sec;       /* seconds */
         long tv_usec;      /* microseconds */
     };
(3)struct timespec有两个成员,一个是秒,一个是纳秒。
     struct timespec{
         time_t  tv_sec;         /* seconds */
         long    tv_nsec;        /* nanoseconds */
     };
(4)struct tm是直观意义上的时间表示方法:
     struct tm {
         int     tm_sec;         /* seconds */
         int     tm_min;         /* minutes */
         int     tm_hour;        /* hours */
         int     tm_mday;        /* day of the month */
         int     tm_mon;         /* month */
         int     tm_year;        /* year */
         int     tm_wday;        /* day of the week */
         int     tm_yday;        /* day in the year */
         int     tm_isdst;       /* daylight saving time */
     };
    
2、 时间操作
(1) 时间格式间的转换函数
  主要是 time_t、struct tm、时间的字符串格式之间的转换。看下面的函数参数类型以及返回值类型:

  char *asctime(const struct tm *tm);
  char *ctime(const time_t *timep);
  struct tm *gmtime(const time_t *timep);
  struct tm *localtime(const time_t *timep);
  time_t mktime(struct tm *tm);
  gmtime和localtime的参数以及返回值类型相同,区别是前者返回的格林威治标准时间,后者是当地时间。
(2) 获取时间函数
  两个函数,获取的时间类型看原型就知道了:
  time_t time(time_t *t);
  int gettimeofday(struct timeval *tv, struct timezone *tz);
  
  
3、 实例:
(1) 实例1:
  struct timeval  now;
  struct tm       tm_cur;
  gettimeofday(&now, 0);
  localtime_r(&now.tv_sec, &tm_cur);

(2) 实例2:
  time_t now;
  time(&now);
(3) 实例3:
  time_t now = time(NULL);
  srand(time(NULL));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值