影者东升 发表于 2021-8-7 13:08:02

c获取时间

1. 获取时间戳gettimeofday(struct  timeval*tv,struct  timezone *tz)
2. time(time_t *t)获取日期
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>

int main() {
    // timestamp
    struct timeval timeval;
    gettimeofday(&timeval, NULL);
    printf("millsec:%d\n", timeval.tv_sec * 1000 + timeval.tv_usec / 1000);
    sleep(1);
    gettimeofday(&timeval, NULL);
    printf("millsec:%d\n", timeval.tv_sec * 1000 + timeval.tv_usec / 1000);

    // date
    time_tseconds;
    struct tm *date;
    time(&seconds);
    date = gmtime(&seconds);

    printf("sec:%d\n", date->tm_sec);
    printf("min:%d\n", date->tm_min);
    printf("hour:%d\n", date->tm_hour);

    printf("day:%d\n", date->tm_mday);
    printf("month:%d\n", date->tm_mon);
    printf("year:%d\n", date->tm_year + 1900);

    return 0;
}



文档来源:51CTO技术博客https://blog.51cto.com/u_2498536/3304160
页: [1]
查看完整版本: c获取时间