asctime - 月零日或 space 填充?

asctime - day of month zero or space padded?

我有以下程序演示 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,即日期字段被 space 填充。

当我用 MSVC 编译和 运行 这个程序时,它会在月份的某天生成带有前导零的日期字符串:Current date and time: Sun Jan 01 00:00:00 2000

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

像往常一样,Microsoft 的(非)标准 C 库的作者没有过多考虑正确实现标准字母。

甚至在原标准C89/C90中出现了以下文字

Description

The asctime function converts the broken-down time in the structure pointed to by timeptr into a string in the form

Sun Sep 16 01:03:52 1973\n[=10=]

using the equivalent of the following algorithm.

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,这意味着十进制数字 space- 填充和右-在 3 个字符宽的字段内对齐.

给定故障时间的结果是 Sun Jan 1 00:00:00 2000,填充 space。


Python 2,直到 2.7.15 一直按原样公开 C 标准库 asctime 输出,减去导致平台相关行为的换行符,现在在 2.7 中.15 已修复为使用带有前导 space 的硬编码格式。 Python 2 文档在其示例中也使用了具有 2 位数日期的日期,这进一步增加了混淆。