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

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

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值