源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

解析Linux下的时间函数:设置以及获取时间的方法

  • 时间:2021-06-11 09:08 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:解析Linux下的时间函数:设置以及获取时间的方法
[b]一、时间函数[/b]
[u]复制代码[/u] 代码如下:
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);
[b]二、设置和获取时间[/b]
[u]复制代码[/u] 代码如下:
#include <stdio.h> #include <time.h> int main(void) { time_t t1; time_t t2; struct tm *my_tm; char buf[128] = {0}; //自Epoch (00:00:00 UTC, January 1,1970)的秒数 [b]t1 = time(&t1); [/b]printf("%d\n", t1); [b]//1355905754 t2 = time(&t2);[/b] sleep(1); printf("%lf\n",[b]difftime(t2, t1)[/b]); [b]//t1,t2相差:1.000000,有时候可以用这个函数来做伪定时器 [/b]printf("%s\n",[b]ctime(&t1)[/b]);[b]//Wed Dec 19 16:29:14 2012 [/b]      //init tm my_tm->tm_year = 2012-1900; my_tm->tm_mon = 12-1; my_tm->tm_mday = 12; my_tm->tm_hour = 12; my_tm->tm_min = 12; my_tm->tm_sec = 12;      [b]//设置时间 t1 = mktime(my_tm); //获取时间[/b] my_tm = localtime(&t1); sprintf(buf, "d-d-d  d:d:d", my_tm->tm_year + 1900, my_tm->tm_mon + 1, my_tm->tm_mday, my_tm->tm_hour, my_tm->tm_min, my_tm->tm_sec); printf("%s\n", buf);[b]//2012-12-12  12:12:12[/b] return 0; }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部