解析Linux下的時間函數:設定以及擷取時間的方法

來源:互聯網
上載者:User

一、時間函數 複製代碼 代碼如下: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);

二、設定和擷取時間複製代碼 代碼如下:#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)的秒數
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

//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;
//設定時間
t1 = mktime(my_tm);
//擷取時間

my_tm = localtime(&t1);
sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
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);//2012-12-12 12:12:12

return 0;
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.