日期格式化输出 C

* bcl_time.h

#ifndef ERRLOG_BCL_TIME_H
#define ERRLOG_BCL_TIME_H

#ifdef __cplusplus
extern "C" {
#endif
void bcl_get_date_time(const char *fmt, char *dt_buf);

#ifdef __cplusplus
};
#endif

#endif //ERRLOG_BCL_TIME_H

* bcl_time.cpp

#include <ctime>
#include <sys/timeb.h>
#include <cstdio>  /* sprintf */
#include <cstring>
#include "bcl_time.h"

#ifdef __cplusplus
extern "C" {
#endif
void bcl_fmt_date_ftime(struct timeb ptime, const char *fmt, char *dt_buf);

void bcl_get_date_time(const char *fmt, char *dt_buf) {
    struct timeb tp;
    ftime(&tp);
    bcl_fmt_date_ftime(tp, fmt, dt_buf);
}

void bcl_fmt_date_ftime(struct timeb ptime, const char *fmt, char *dt_buf) {
    int i, k;
    int fmt_len;
    struct tm tm;

    tm = *localtime(&(ptime.time));
    k = i = 0;
    fmt_len = strlen(fmt);
    do {
        if (fmt[i] == '%') {
            switch (fmt[i + 1]) {
                case 'Y':
                case 'y':
                    sprintf(&dt_buf[k], "%04d", tm.tm_year + 1900);
                    k += 4;
                    break;
                case 'M':
                case 'm':
                    sprintf(&dt_buf[k], "%02d", tm.tm_mon + 1);
                    k += 2;
                    break;
                case 'D':
                case 'd':
                    sprintf(&dt_buf[k], "%02d", tm.tm_mday);
                    k += 2;
                    break;
                case 'H':
                case 'h':
                    sprintf(&dt_buf[k], "%02d", tm.tm_hour);
                    k += 2;
                    break;
                case 'I':
                case 'i':
                    sprintf(&dt_buf[k], "%02d", tm.tm_min);
                    k += 2;
                    break;
                case 'S':
                case 's':
                    sprintf(&dt_buf[k], "%02d", tm.tm_sec);
                    k += 2;
                    break;
                case 'U':
                case 'u':
                    sprintf(&dt_buf[k], "%03d", ptime.millitm);
                    k += 3;
                    break;
                default:
                    dt_buf[k++] = fmt[i + 1];
                    break;
            }
            i += 1;
        } else {
            dt_buf[k++] = fmt[i];
        }
        i++;
    } while (i < fmt_len);
    dt_buf[k] = 0;
    return;
}

#ifdef __cplusplus
};
#endif

#include "bcl_time.h"
char dt_buf[20];
bcl_get_date_time("%y-%M-%d %H:%i:%s", dt_buf);

std::cout << "Hello, World! " << dt_buf << std::endl;

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值