日期格式化输出 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 
#include 
#include   /* sprintf */
#include 
#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;

日期格式化输出 C_第1张图片

 

你可能感兴趣的:(c语言)