用C格式化日期

时间:2015-12-09 13:59:15

标签: c date

我有一些GPS字符串日期如下:

 "181215" //11th Dec 2015
 "211115" //21st Nov 2015

我可以使用这种格式,但是当日期或月份是一位数时,它看起来像:

 "11215" //1st Dec 2015
 "8515" //8th May 2015

在C中将8515转换为080515的最佳方法是什么?

我基本上需要把字符串变成3个整数,我这样做:

//date: 171115
char str[8];
sprintf(str, "%d", date);
char component[3];

sprintf(component,"%c%c",str[0],str[1]);
int day = strtof(component, NULL);

sprintf(component,"%c%c",str[2],str[3]);
int month = strtof(component, NULL);

sprintf(component,"%c%c",str[4],str[5]);
int year = strtof(component, NULL) + 2000;

2 个答案:

答案 0 :(得分:1)

试试这样:

DynamicResource

然后像以前一样继续。

答案 1 :(得分:1)

这是一个为模糊日期提供可识别错误输出的解决方案:

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

/* N.B. returns a pointer to static storage - not for production use */
/* Returns "??????" on failure */
const char *reformat(const char *s)
{
    static char buf[9];

    int d, m, y;                /* day, month, year */
    switch (strlen(s)) {
    case 6:
        return s;
    case 5:
        if (s[1] == '1' && s[2] <= '2') {
            /* second digit may be part of day or month */
            if (s[0] <= '2' || s[0] <= '3' && s[2] == '1')
                return "??????";              /* ambiguous string */
            /* 1-digit day, 2-digit month */
            sscanf(s, "%1d%2d%2d", &d, &m, &y);
        break;
        }
        /* 2-digit day; 1-digit month */
        sscanf(s, "%2d%1d%2d", &d, &m, &y);
        break;
    case 4:
        sscanf(s, "%1d%1d%2d", &d, &m, &y);
        sprintf(buf, "%02d%02d%02d", d, m, y);
        return buf;
    default:
        return "??????";              /* invalid input length */
    };
    sprintf(buf, "%02d%02d%02d", d, m, y);
    return buf;
}

这是一个测试程序:

int main(int argc, char **argv)
{
    while (*++argv)
        printf("%6s -> %s\n", *argv, reformat(*argv));
    return 0;
}

在我的测试用例中,它产生:

   111 -> ??????
  8515 -> 080515
181215 -> 181215
  1111 -> 010111
 11215 -> ??????
 31211 -> 031211
 29212 -> 290212
 21200 -> ??????
 21300 -> 210300
11111111 -> ??????