c语言使用time函数

看了两遍博客是关于C语言时间函数的, 分别是https://blog.csdn.net/wangluojisuan/article/details/7045592 和https://www.cnblogs.com/caolisong/archive/2007/04/11/709732.html。

简单写了个自己的例子,以实现收集log的文件命名都以年月日时分秒命令。

另外, 使用时间函数,要添加头文件time.h 

C语言表示时间有两种形式:

1. time_t

2. struct tm 形式

    struct  tm{
           int tm_sec;
           int tm_min;
           int tm_hour;
           int tm_mday;
           int tm_mon;
           int tm_year;
           int tm_wday;
           int tm_yday;
           int tm_isdst;
         };

3. 代码是想以年月日时分秒的形式打印出来,借用stftime函数,正好将时间格式化为我们想要的格式。它的原型如下:

size_t strftime(
     char *strDest,
     size_t maxsize,
     const char *format,
     const struct tm *timeptr
);

可以根据format指向字符串中格式命令把timeptr中保存的时间信息放在strDest指向的字符串中,最多向strDest中存放maxsize个字符。该函数返回向strDest指向的字符串中放置的字符数。

函数strftime()的操作有些类似于sprintf():识别以百分号(%)开始的格式命令集合,格式化输出结果放在一个字符串中。格式化命令说明串strDest中各种日期和时间信息的确切表示方法。格式串中的其他字符原样放进串中。

格式命令列参考https://www.cnblogs.com/caolisong/archive/2007/04/11/709732.html,它们是区分大小写的。我所用到的是:

%F 年-月-日

%T 显示时分秒:hh:mm:ss

代码放在: http://codepad.org/J9IKeHnt ,可以自行在线编译

#include <stdio.h>
#include <time.h>
//https://blog.csdn.net/wangluojisuan/article/details/7045592
int main()
{

    time_t timer = time(NULL);
    struct tm* localTime = localtime(&timer);
    printf("ascii time is : %s\n", asctime(localTime));
    char date[100] = {0};
    strftime(date, 100, "%F-%T", localTime);
    printf("local time is : %s\n", date);
    return 0;
}
 > g++ test_time.cpp
 > ./a.out
ascii time is : Sat Sep 15 10:19:24 2018

local time is : 2018-09-15-10:19:24

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值