asctime-每月的零号还是空格?

时间:2018-12-22 08:28:46

标签: c visual-c++ language-lawyer msvcrt time.h

我有以下程序演示了asctime的使用。

#include <stdio.h>
#include <time.h>

int main(void) {
    struct tm   broken_down;
    broken_down.tm_year = 2000 - 1900;
    broken_down.tm_mon = 0;
    broken_down.tm_mday = 1;
    broken_down.tm_hour = broken_down.tm_min = broken_down.tm_sec = 0;

    printf("Current date and time: %s", asctime(&broken_down));
}

该程序在ideone.com上打印Current date and time: Sun Jan 1 00:00:00 2000,即日期字段为空格。

当我使用MSVC编译并运行该程序时,它会在日期Current date and time: Sun Jan 01 00:00:00 2000中产生前导零的日期字符串。

这种差异的原因是什么?哪种格式正确?

1 个答案:

答案 0 :(得分:6)

像往常一样,微软(非)标准C库的作者并没有过多考虑正确实施标准字母的问题。

即使在原始标准C89/C90中,也会显示以下文字

  

说明

     

asctime函数转换结构中的细分时间   timeptr指向格式为

的字符串
Sun Sep 16 01:03:52 1973\n\0
     

使用与以下算法等效的方法。

char *asctime(const struct tm *timeptr)
{
    static const char wday_name[7][3] = {
             "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
    };
    static const char mon_name[12][3] = {
             "Jan", "Feb", "Mar", "Apr", "May", "Jun",
             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
    };
    static char result[26];

    sprintf(result, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
             wday_name[timeptr->tm_wday],
             mon_name[timeptr->tm_mon],
             timeptr->tm_mday, timeptr->tm_hour,
             timeptr->tm_min, timeptr->tm_sec,
             1900 + timeptr->tm_year);
    return result;
}

不幸的是,示例本身使用的日期是每月2位数字的日期,但是代码使用%3d,这意味着用小数位填充空格并在3个字符范围内右对齐字段

在给定的细分时间下,结果为Sun Jan 1 00:00:00 2000(使用空格填充)。


Python 2直到2.7.15之前都按原样公开了C标准库asctime的输出,但导致平台相关行为的换行符已在2.7.15中固定为使用具有前导空格的硬编码格式。同样,Python 2文档在其示例中使用的日期是每月两位数的日期,这进一步加剧了混乱。

相关问题