技术宅,fat-man

增加语言的了解程度可以避免写出愚蠢的代码

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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;
}
复制代码

 

 

 

posted on   codestyle  阅读(1140)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示