如何检查日期是否存在C.

时间:2014-10-09 05:05:45

标签: c validation date

如果我有以下用户输入:年,月和日。如何检查date是否确实存在过?

例如:2014-10-32 (FALSE)2014-09-31 (FALSE)2009-02-28 (TRUE)

2 个答案:

答案 0 :(得分:1)

如果无法表示日历时间,则C API中的

mktime()将返回-1。以下代码段可以帮助您检查相同的内容(给定nDay,月nMonth和年nYear作为参数):

tm tmDate;
memset( &tmDate, 0, sizeof(tm) );
tmDate.tm_mday = nDay;
tmDate.tm_mon = (nMonth - 1);
tmDate.tm_year = (nYear - 1900);

time_t tcal= mktime( &tmDate);
if( tcal == (time_t) -1 ) return false;

以上片段说明了这个想法。可以在http://www.codeproject.com/Articles/4722/How-to-check-if-a-datetime-exists

找到更强大的代码

答案 1 :(得分:0)

像这样的SomeThing可以帮助你:

// This calendar example

#include<stdio.h>

#define TRUE    1
#define FALSE   0

int days_in_month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};
char *months[]=
{
    " ",
    "\n\n\nJanuary",
    "\n\n\nFebruary",
    "\n\n\nMarch",
    "\n\n\nApril",
    "\n\n\nMay",
    "\n\n\nJune",
    "\n\n\nJuly",
    "\n\n\nAugust",
    "\n\n\nSeptember",
    "\n\n\nOctober",
    "\n\n\nNovember",
    "\n\n\nDecember"
};


int inputyear(void)
{
    int year;

    printf("Please enter a year (example: 1999) : ");
    scanf("%d", &year);
    return year;
}

int determinedaycode(int year)
{
    int daycode;
    int d1, d2, d3;

    d1 = (year - 1.)/ 4.0;
    d2 = (year - 1.)/ 100.;
    d3 = (year - 1.)/ 400.;
    daycode = (year + d1 - d2 + d3) %7;
    return daycode;
}


int determineleapyear(int year)
{
    if(year% 4 == FALSE && year%100 != FALSE || year%400 == FALSE)
    {
        days_in_month[2] = 29;
        return TRUE;
    }
    else
    {
        days_in_month[2] = 28;
        return FALSE;
    }
}

void calendar(int year, int daycode)
{
    int month, day;
    for ( month = 1; month <= 12; month++ )
    {
        printf("%s", months[month]);
        printf("\n\nSun  Mon  Tue  Wed  Thu  Fri  Sat\n" );

        // Correct the position for the first date
        for ( day = 1; day <= 1 + daycode * 5; day++ )
        {
            printf(" ");
        }

        // Print all the dates for one month
        for ( day = 1; day <= days_in_month[month]; day++ )
        {
            printf("%2d", day );

            // Is day before Sat? Else start next line Sun.
            if ( ( day + daycode ) % 7 > 0 )
                printf("   " );
            else
                printf("\n " );
        }
            // Set position for next month
            daycode = ( daycode + days_in_month[month] ) % 7;
    }
}

int main(void)
{
    int year, daycode, leapyear;

    year = inputyear();
    daycode = determinedaycode(year);
    determineleapyear(year);
    calendar(year, daycode);
    printf("\n");
}

了解详情CodeInGunit