C语言日期时间标准库

用思维导图整理:

代码:

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

int main()
{
    /* 标准库直接支持 */
    //获得运行程序的机器时间,并直接从time_t打印时间
    time_t t = time(NULL);
    printf("%s
",ctime(&t));

    //从time_t转换成为struct tm,使用struct tm打印时间
    struct tm *ptm = localtime(&t);
    printf("%s
",asctime(ptm));
    
    //自定义打印时间样式
    const int BUF_SIZE = 1024;
    char buffer[BUF_SIZE] = {0};
    strftime((char*)&buffer,BUF_SIZE,"%Y-%m-%d",ptm);
    printf("%s
",&buffer);

    /*将time_t转成long int储存,再读入转成time_t,打印,这个模拟的是从数据库读出再处理*/
    time_t new_t = time(NULL);
    printf("%s
",ctime(&new_t));
    long int stored = (long int)new_t;
    time_t get_t = (time_t) stored;
    printf("%s
",ctime(&get_t));

    /* 貌似可以直接初始化 struct tm ,但是我不确定和不和具体编译器有关*/
    struct tm mytm;
    memset(&mytm,0,sizeof(mytm));
    mytm.tm_year = 113; //1900 年开始计数
    mytm.tm_mon  = 8;   //0~11表示1~12个月
    mytm.tm_mday = 1;
    mytm.tm_hour = 15;
    mytm.tm_min  = 9;
    mytm.tm_sec  = 1;
    printf("%s
",asctime(&mytm));

    /* C语言里把描述日期时间的字符串转成time_t或struct tm比较困难,因为标准库不直接支持 */

    return 0;
}
原文地址:https://www.cnblogs.com/code-style/p/3294532.html