date实现

UNIX系统内部对时间的表示方式均是自Epoch以来的秒数来度量的,Epoch亦即通用协调时间的1970年1月1日早晨零点。

这是UNIX系统问世的大致日期,日历时间存储于类型为time_t的变量中。

系统调用gettimeofday(),可于tv指向的缓存区中返回日历时间。

#include <sys/time.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);

                          Returns 0 on success, or -1 on error

参数tv是指向如下数据结构的一个指针:

struct timeval {

  time_t tv_sec;  /*Seconds since 00:00:00, 1 Jan 1970 UTC*/

  suseconds_t tv_usec;

};

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

int main() {
    struct timeval tv;
    int val;
    char *day;

    val=gettimeofday(&tv, NULL);
    if(val == 0) {
        printf("%ld\n", (long)tv.tv_sec);
    }
    day=ctime(&tv.tv_sec);
    if(day != NULL) {
        printf("%s", day);
    }

    return 0;
}

1649938542
Thu Apr 14 20:15:42 2022

posted @ 2022-04-14 20:22  东宫得臣  阅读(23)  评论(0编辑  收藏  举报