time & localtime

tm 结构

struct tm {
    int tm_sec;         // seconds
    int tm_min;         // minutes
    int tm_hour;        // hours
    int tm_mday;        // day of the month
    int tm_mon;         // month [0~11]
    int tm_year;        // year, form 1900
    int tm_wday;        // day of the week
    int tm_yday;        // day in the year
    int tm_isdst;       // daylight saving time
};

用法示例

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

int main()
{
    /*
     * time_t time(time_t *seconds);返回自纪元
     * Epoch(1970-01-01 00:00:00 UTC)起经过
     * 的时间,以秒为单位。
     */
    /*如果seconds不为空,则返回值也会存储在seconds中*/
    time_t sec = time(NULL);
    /*
     * struct tm *localtime(const time_t *timep);
     * 将时间数值变换成本地时间
     */
    struct tm *local_time = localtime(&sec);
    printf("localtime: %d/%d/%d--%d:%d:%d
", local_time->tm_year + 1900, local_time->tm_mon + 1, 
           local_time->tm_mday, local_time->tm_hour, local_time->tm_min, local_time->tm_sec);
    /*
     * char *asctime(const struct tm *tm);
     * 该函数返回一个 C 字符串,包含了可读格式的日期和时间信息 Www Mmm dd hh:mm:ss yyyy,
     * 其中,Www 表示星期几,Mmm 是以字母表示的月份,dd 表示一月中的第几天,hh:mm:ss 表示时间,
     * yyyy 表示年份。
     */
    char *time_buf = asctime(local_time);
    printf("asctime-->localtime: %s
", time_buf);
    return 0;
}

输出结果:

$ ./time
localtime: 2018/7/22--22:46:51
asctime-->localtime: Sun Jul 22 22:46:51 2018
原文地址:https://www.cnblogs.com/shelmean/p/9351053.html