Linux/C

C 时间函数使用

2019-12-14  本文已影响0人  国服最坑开发

0x01 主要涉及对象

struct timespec
{
  __time_t tv_sec;      /* Seconds.  */
  __syscall_slong_t tv_nsec;    /* Nanoseconds.  */
};
struct tm
{
  int tm_sec;           /* Seconds. [0-60] (1 leap second) */
  int tm_min;           /* Minutes. [0-59] */
  int tm_hour;          /* Hours.   [0-23] */
  int tm_mday;          /* Day.     [1-31] */
  int tm_mon;           /* Month.   [0-11] */
  int tm_year;          /* Year - 1900.  */
  int tm_wday;          /* Day of week. [0-6] */
  int tm_yday;          /* Days in year.[0-365] */
  int tm_isdst;         /* DST.     [-1/0/1]*/

# ifdef __USE_MISC
  long int tm_gmtoff;       /* Seconds east of UTC.  */
  const char *tm_zone;      /* Timezone abbreviation.  */
# else
  long int __tm_gmtoff;     /* Seconds east of UTC.  */
  const char *__tm_zone;    /* Timezone abbreviation.  */
# endif
};

0x02 使用例:

#include <sys/stat.h>
#include <time.h>


char *cc_time_2_str(struct timespec ts) {
    struct tm t;
    char      *buf = (char *) malloc(64);
    strftime(buf, 64, "%Y-%m-%d %H:%M:%S", localtime_r(&ts.tv_sec, &t));
    return buf;
}

struct timespec *cc_get_system_time() {
    struct timespec *curr_time = (struct timespec *) malloc(sizeof(struct timespec));
    if (clock_gettime(CLOCK_REALTIME, curr_time) != 0)
        exit(1);
    return curr_time;
}


int main(int argc, char *argv[]) {

    struct timespec *now     = cc_get_system_time();
    char            *now_str = cc_time_2_str(*now);
    printf("time now is %s\n", now_str);
    free(now_str);
    free(now);

    exit(0);
}

为了方便使用, 函数设计时,还是习惯在函数内部返回一个malloc 指针, 外部 free 即可.

上一篇下一篇

猜你喜欢

热点阅读