C语言日期时间标准库

用思维导图整理:

代码:

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

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

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

    /*将time_t转成long int储存,再读入转成time_t,打印,这个模拟的是从数据库读出再处理*/
    time_t new_t = time(NULL);
    printf("%s\n",ctime(&new_t));
    long int stored = (long int)new_t;
    time_t get_t = (time_t) stored;
    printf("%s\n",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\n",asctime(&mytm));

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

    return 0;
}

 

 

 

转载于:https://www.cnblogs.com/code-style/p/3294532.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值