C - 時間處理




取得秒數

gettimeofday

定義:

    #include <sys/time.h>
    int gettimeofday(struct timeval *tv, struct timezone *tz);


範例:

struct timeval tv;
gettimeofday(&tv, NULL);

tv.tv_sec:秒數 (型態:long int)
tv.tv_usec:微秒 (型態:long int)


time

定義:

    #include <time.h>
    time_t time(time_t *tloc);


範例:

time_t t = time(NULL);



時間結構


struct tm {
int tm_sec; /* Seconds (0-60) */
int tm_min; /* Minutes (0-59) */
int tm_hour; /* Hours (0-23) */
int tm_mday; /* Day of the month (1-31) */
int tm_mon; /* Month (0-11) */
int tm_year; /* Year - 1900 */
int tm_wday; /* Day of the week (0-6, Sunday = 0) */
int tm_yday; /* Day in the year (0-365, 1 Jan = 0) */
int tm_isdst; /* Daylight saving time */
};
struct tm *tm;
tm = localtime(&tv.tv_sec);

年:tm->tm_year + 1900
月:tm->tm_mon + 1
日:tm->tm_mday
時:tm->tm_hour
分:tm->tm_min
秒:tm->tm_sec


長整數換成字串(時間格式)

定義:

    #include <time.h>
    time_t time(time_t *tloc);
    struct tm *localtime(const time_t *timep);
    struct tm *gmtime(const time_t *timep);
    size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);


範例:
{
char outstr[200];
time_t t = time(NULL);
struct tm *tmp = localtime(&t); // (考慮時區)
struct tm *tmp = gmtime(&t); // (+0時區)
strftime(outstr, sizeof(outstr), "%F %T", tmp); //等於 %Y-%m-%d %H:%M:%S
}



字串(時間格式)換成長整數

定義:

    #include <time.h>
    time_t mktime(struct tm *tm);
    char *strptime(const char *s, const char *format, struct tm *tm);


範例:

    struct tm tm;
    char buf[] = "2024-03-15 11:45:00"
    strptime(buf ,"%Y-%m-%d %H:%M:%S", &tm);
    time_t t = mktime(&tm);



常用參數


    %F: 等同 %Y-%m-%d
    %T: 等同 %H:%M:%S
    %R: 等同 %H:%M
    %Y: 年, 2024
    %m: 月 (112)
    %d: 日 (131)
    %H: 時 (24小時制) (023)
    %I: 時 (12小時制) (112)
    %M: 分 (059)
    %S: 秒 (060)
    %s: 從 1970-01-01 00:00:00 +0000 算起的秒數
    %w: 星期 (06), 星期日 = 0



我的 lib


tv.tv_sec += (atoi(RS(GLOBAL_COLCK_OFFSET)) * 3600);










沒有留言:

張貼留言