Loading

获取系统时间:格式(YYYY-MM-DD HH:MM:SS)

一、前言#

在写程序时,常常会用到系统时间,如果利用好 ANSI C 基本的库(time.h),输出格式为:YYYY-MM-DD HH:MM:SS 的字符串呢? 若将这个功能写成函数,可以提高代码的复用率。

二、获取系统时间#

实现代码:

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

static int lib_system_datetime_string_get(char datetime[256])
{
    time_t t;
    struct tm *lt;
    time(&t);
    lt = localtime(&t);
    strftime(datetime, 100, "%Y-%m-%d %H:%M:%S", lt);
    return 0;
}

/* 时间精确到ms */
static int lib_system_datetime_ms_string_get(char datetime[256])
{
    struct tm *tm_t;
    struct timeval time;
    gettimeofday(&time,NULL);
    tm_t = localtime(&time.tv_sec);
    if(NULL != tm_t) 
    {
        snprintf(datetime, 50, "%04d-%02d-%02d %02d:%02d:%02d.%03ld",
            tm_t->tm_year+1900,
            tm_t->tm_mon+1, 
            tm_t->tm_mday,
            tm_t->tm_hour, 
            tm_t->tm_min, 
            tm_t->tm_sec,
            time.tv_usec/1000);
    }
    return 0;
}

int main(void)
{
    char time_txt[256] = {0};
    lib_system_datetime_string_get(time_txt);  
    printf("%s\n", time_txt);
    return 0;
}

运行结果:

三、计算时间差#

实现代码
在Windows环境下:

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

int main(void)
{
    time_t t1, t2;
    double diff = 0;
    time(&t1);
    Sleep(2000);
    time(&t2);
    diff = difftime(t2, t1);
    printf("时间差: %f", diff);

    return 0;
}

运行结果

在Linux环境下实现:

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

int main(void)
{
    time_t time1, time2;
    time1 = time((time_t *) NULL);
    sleep(3);
    time2 = time((time_t *) NULL);
    printf("use %.2f s\n", difftime(time2, time1));
    exit(0);
}

四、参考来源#

01-ctime<time.h>

作者:caojun97

出处:https://www.cnblogs.com/caojun97/p/16982191.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   eiSouthBoy  阅读(492)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu