linux 時間格式轉換


1:頭文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>     // sleep 函數頭文件
#include <time.h>       // 結構體time_t和函數time
#include <sys/time.h>   // 結構體timeval和函數select,gettimeofday的頭文件


2:取得當前時間 精確到秒 轉換為日期形式

    time_t nowT ;      // time_t就是long int 類型
    nowT = time(0);    // 取得當前時間 ,秒級
    // time(&nowT);    // 取得當前時間 ,秒級
    // nowT = time(NULL); // 取得當前時間 ,秒級
    char strT[32];
    /* 使用 strftime 將時間格式化成字符串("YYYY-MM-DD hh:mm:ss"格式)*/
    strftime(strT, sizeof(strT), "%Y-%m-%d %H:%M:%S", localtime(&nowT));
    printf("%s\n",strT);
    strftime(strT, sizeof(strT), "%Y/%m/%d %H:%M:%S", localtime(&nowT));
    printf("%s\n",strT);

3:取得當前時間 精確到微妙 轉換為日期形式

    /* 取得當前時間 精確到微妙 轉換為日期形式 */
    struct timeval nowTus;
    // nowTus.tv_sec = 1; (秒)
    // nowTus.tv_usec = 100000;(微妙)
    gettimeofday( &nowTus, NULL ); // 取的當前時間秒數、 毫秒級
    // struct tm* nowTm = localtime(&nowTus.tv_sec);  
    // localtime  將秒轉換為年月日時分秒格式,為非線程安全函數
    struct tm nowTm2;    // localtime
    localtime_r( &nowTus.tv_sec, &nowTm2 ); //localtime_r 為線程安全函數,建議使用。
    char strT2[32];
    snprintf(strT2, sizeof(strT2), "%04d/%02d/%02d %02d:%02d:%02d:%03dms",
            nowTm2.tm_year + 1900, nowTm2.tm_mon + 1, nowTm2.tm_mday,
            nowTm2.tm_hour, nowTm2.tm_min,nowTm2.tm_sec, nowTus.tv_usec / 1000);
    printf("%s\n",strT2); // 方法 1
    strftime(strT2, sizeof(strT2), "%Y-%m-%d %H:%M:%S", &nowTm2);
    printf("%s:%03dms\n",strT2,nowTus.tv_usec / 1000); // 方法 2

4:將"YYYY-MM-DD hh:mm:ss"格式的時間轉換為秒

    char strT3[] = "2013/01/02 00:25:00";
    struct tm nowTm3;
    strptime(strT3,"%Y/%m/%d %H:%M:%S",&nowTm3); // 將"YYYY-MM-DD hh:mm:ss" 轉換為tm
    time_t longT = mktime(&nowTm3); // 將 tm 轉換為1970年以來的秒
    fprintf(stdout, "strT3=%s ,longT=%ld\n", strT3,(long)longT);


5:ctime 將時間轉化為"Mon Nov  7 09:52:59 2016"形式

    /*ctime 將時間轉化為"Mon Nov  7 09:52:59 2016"形式,加上一個換行符共25個字符*/
    time_t nowT4 = time(0);    // 取得當前時間 ,秒級
    char* pT = ctime(&nowT4);
    char strT4[26];
    memcpy(strT4, pT, 26);
    printf("ctime time is: %s", strT4);   // ctime 直接將秒轉換成日期
    struct tm nowTm4;
    localtime_r( &nowT4, &nowTm4 );
    printf("asctime time is: %s", asctime(&nowTm4)); // asctime把tm 的數據轉換成字符串

6:sleep select使用

    /* sleep select (設定等待時間,sleep線程內等待,select線程掛起節省CPU資源) */
    sleep(1);            // #include <unistd.h> 單位:秒
    usleep(1000000);     // #include <unistd.h> 單位:微妙

    struct timeval wait_time;
    wait_time.tv_sec = 1;                        //
    wait_time.tv_usec = 100000;                  //微妙
    // 在linux 內核2.6 以后的版本,select會清空最后一個參數的值
    // 因此若在循環體使用select的話,必須每次都賦值
    select(0, NULL, NULL, NULL, &wait_time);     //使用select等待    ,10

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM