欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Linux下C语言实现获取当前时间

程序员文章站 2024-01-29 10:55:40
...

C语言获取当前时间

简介

在工作中,经常涉及到获取当前时间,用于写日志,基于此,今特意利用C语言写一个获取时间函数,用于后面用到时,能够及时查到。获取当前时间,要用到time.h中的time()和localtime()函数,二者具体介绍与使用,参见 https://blog.csdn.net/yzhang6_10/article/details/51583894

具体实现

程序实现

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

void gettime(char *cur_time) {
        char Year[6] = {0};
        char Month[4] = {0};
        char Day[4] = {0};
        char Hour[4] = {0};
        char Min[4] = {0};
        char Sec[4] = {0};

        time_t current_time;
        struct tm* now_time;
        time(&current_time);
        now_time = localtime(&current_time);

        strftime(Year, sizeof(Year), "%Y-", now_time);
        strftime(Month, sizeof(Month), "%m-", now_time);
        strftime(Day, sizeof(Day), "%d ", now_time);
        strftime(Hour, sizeof(Hour), "%H:", now_time);
        strftime(Min, sizeof(Min), "%M:", now_time);
        strftime(Sec, sizeof(Sec), "%S", now_time);

        strncat(cur_time, Year, 5);
        strncat(cur_time, Month, 3);
        strncat(cur_time, Day, 3);
        strncat(cur_time, Hour, 3);
        strncat(cur_time, Min, 3);
        strncat(cur_time, Sec, 3);
}

int main() {
        char *cur_time = (char *)malloc(21*sizeof(char));
        gettime(cur_time);
        printf("Current time: %s\n", cur_time);
        free(cur_time);
        cur_time = NULL;
        return 0;
}

程序编译: g++ test_time.cpp -o test_time

程序执行结果:Current time: 2018-08-08 00:11:31