C中的日期格式

时间:2017-04-11 03:32:05

标签: c

我正在尝试将以dd / mm / yyyy格式输入的日期更改为月份日,年份格式,并且我已经完成了大部分工作但是我的输出在一天之后添加了一个额外的怪异角色。这是我的代码

#include <stdio.h>
#include <string.h>
void main()
{
    char userDate[11];
    char dateWord[11];
    char day[2];
    char year[4];
    printf("Welcome to the Date Formatter.\nPlease input a date in the form of mm/dd/yyyy.\n");
    scanf("%s", userDate);

    day[0] = userDate[3];
    day[1] = userDate[4];
    year[0] = userDate[6];
    year[1] = userDate[7];
    year[2] = userDate[8];
    year[3] = userDate[9];

    if (userDate[0] == '0' && userDate[1] == '1')
        strcpy(dateWord, "January");
    if (userDate[0] == '0' && userDate[1] == '2')
        strcpy(dateWord, "February");
    if (userDate[0] == '0' && userDate[1] == '3')
        strcpy(dateWord, "March");
    if (userDate[0] == '0' && userDate[1] == '4')
        strcpy(dateWord, "April");
    if (userDate[0] == '0' && userDate[1] == '5')
        strcpy(dateWord, "May");
    if (userDate[0] == '0' && userDate[1] == '6')
        strcpy(dateWord, "June");
    if (userDate[0] == '0' && userDate[1] == '7')
        strcpy(dateWord, "July");
    if (userDate[0] == '0' && userDate[1] == '8')
        strcpy(dateWord, "August");
    if (userDate[0] == '0' && userDate[1] == '9')
        strcpy(dateWord, "September");
    if (userDate[0] == '1' && userDate[1] == '0')
        strcpy(dateWord, "October");
    if (userDate[0] == '1' && userDate[1] == '1')
        strcpy(dateWord, "November");
    if (userDate[0] == '1' && userDate[1] == '2')
        strcpy(dateWord, "December");


    printf("The date is:\n");
    printf("%s %s, %s\n", dateWord, day, year);
}

输出

c:\CompSci\C Programming>dateconvert
Welcome to the Date Formatter.
Please input a date in the form of mm/dd/yyyy.
01/23/1998
The date is:
January 23╢ , 1998

我不确定为什么要打印。。

1 个答案:

答案 0 :(得分:5)

已经有日期解析和格式化功能,strptimestrftime。所以你可以使用它们。首先,使用strptime将日期解析为struct tm

#include <time.h>

struct tm date;
strptime( userDate, "%m/%d/%Y", &date );

日期现在位于struct tm,您可以使用正常日期函数(包括strftime)对其进行操作以进行格式化。

char formatted_date[40];
strftime( formatted_date, 40, "%B %d, %Y", &date );
puts( formatted_date );

使用strftime的一个好处是它会尊重用户的语言环境并以适当的语言提供月份。默认情况下,C不会尊重语言区域,您必须从locale.h拨打setlocale (LC_ALL, "");

$ ./test
Welcome to the Date Formatter.
Please input a date in the form of mm/dd/yyyy.
01/02/1999
January 02, 1999

$ LC_ALL=es_ES ./test
Welcome to the Date Formatter.
Please input a date in the form of mm/dd/yyyy.
01/02/1999
enero 02, 1999

请注意,您的scanf应限制为userDate缓冲区的大小,否则可能会超出缓冲区。 %s 总是有限制。

scanf("%10s", userDate);

虽然有些编译器会接受void main,但它是非标准的。它应始终为int main