Check whether a date is valid in C or not?

Asked

Viewed 5,789 times

1

I need to check if a date is valid or not in C, and for this I will have a function called verificarData that will be passed to it the user input and will check whether or not it is a valid date.

But I’m in doubt, because I’ll have to break this to pieces data to check whether it contains :

  1. Contains two bars between date

  2. If the day is between 1 and 31.

  3. If the month is between 1 and 12.

  4. Year between 1900 and 2100

  5. If month is 04, 06, 09 or 11, day can be maximum 30;

  6. If month is 02, day can be maximum 28;

  7. If year is leap and month is 02, day can be maximum 29.

Which is better to use in case ? Use vetor or even char and try to break the date and do the proper checks, and if I can use with char, how to break it into pieces to check ?

For example, if the user enters the following value :

Input : 20/03/2009

How can I break for you to stay, 20/, 03/ and 2009 separated so I can check ?

I also need to check if the day, month and year are numerical, but as I’m putting bars with numbers I can’t use the function isdigit to verify.

Example :

if(isdigit(data)) {
printf("São numéricos.");
}
else {
printf("Não são numéricos.");
}

But it returns as if they are not numbers even the user putting the day, the month and the year with numbers, because because of the bars, it returns as if it were a string. How can I check and return saying if they are numbers or not correctly ?

  • for each of the cases, what is the expected result? Some kind of message to the user or are only validations?

  • Only validations, a message will be sent to the user only if after checking whether or not the date is validated.

3 answers

2


For example, if the user enters the following value :

Input : 20/03/2009

How can I break for you to stay, 20/, 03/ and 2009 separated so I can check?

Function

Use the functions below.

  • strtok - breaks a string into tokens, given a specific delimiter (use /).

  • strtol - converts a string to a long integer.

  • strstr - finds the first occurrence of a specific substring in a string (use //).

  • isdigit - checks if the character passed as argument is a digit.

Logic

Code base below. Also see working online here.

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

int verificarNumero(char *entrada) {
  int i;

  for (i = 0; entrada[i] != '\0'; i++)
  {
    if (entrada[i] != '/' && !isdigit(entrada[i]))
    {
      return 0;
    }
  }

  return 1;
}

int verificarData(char *entrada)
{
  const char substring[3] = "//";

  if (strstr(entrada, substring) != NULL)
  {
    return 0;
  }

  if (verificarNumero(entrada))
  {
    printf("São numéricos.\n");
  }
  else
  {
    printf("Não são numéricos.\n");
    return 0;
  }

  int i = 0;
  long data[3];
  const char delimitador[2] = "/";
  char *token = strtok(entrada, delimitador);

  // Alimenta o vetor de inteiros
  while (token != NULL)
  {
    data[i++] = strtol(token, NULL, 10);
    token = strtok(NULL, delimitador);
  }

  // Realize suas validações. Se alguma não for atingida, retorne '0'

  printf("Dia: %d\n", data[0]);
  printf("Mes: %d\n", data[1]);
  printf("Ano: %d\n", data[2]);

  // Caso contrário, retorne '1'

  return 1;
}

int main()
{
  char str[80];

  printf("Digite uma data: ");
  gets(str);

  printf("%d\n", verificarData(str));

  return(0);
}
  • Thank you very much for the explanation, I will make the appropriate modifications and return later to tell you whether it worked or not.

  • Does not work your code, at least not the way I wanted, it does not break the date once, because by showing by the printf it shows the date incorrectly.

  • What do you mean, @Monteiro? Online example here, what’s wrong with it?

  • In this new online example of yours, it did work, thank you very much. But now I need to check if it really has two bars a date, for example, with an if, if the user has only put one bar on the date then it returns 0 to the program and if it has put two, returns 1.

  • @Monteiro updated the answer and the online example.

  • 1

    Thank you very much, it worked right your code, and on top of that I learned new things in C, and I have updated my code here with the appropriate if-lse to do the check and it worked. + 1 and right answer too.

  • One last question, how can I check whether date is a number or a string ? I’m trying to use isdigit but as it contains bars, it returns as false the result and says they are not numbers.

  • @Monteiro I don’t know if I understood it right. You can give an example of input?

  • I have to check if the user input is a number or a string. The day, month and year need to be numerical, and then I need to do this check. I will put this example of what I want in my question.

  • @Monteiro updated the answer. isdigit() receives only one character at a time. You need to access each character of the string to do the check, as shown in the example.

  • Perfect, thank you so much for everything. Ali no ! isdisgit(input[i]) is checking if it is not different right ?

  • !isdisgit(entrada[i]) is true when entrada[i] nay is a digit, false when it’s a digit.

  • All right, I get it, thank you very much for the explanation of the code and the code itself, it helped me a lot.

Show 8 more comments

-1

Function to validate a date in the format dd/mm/yy: The string containing the date will have a fixed size whenever it is 11 counting with the control character ' 0', all that needs to be done is to convert the carcter representing the day/ month and the year and check its valid limits.

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

int valid(char *date)
{
int tmp=0,tmp1=0,tmp2=0,flag=0;
if(strlen(date)<=10){
tmp=(date[0]-'0')*10+(date[1] - '0');
if(tmp > 0 && tmp <32) flag++;
tmp1=(date[3]-'0')*10+(date[4]-'0');
if(tmp1 > 0 && tmp1 <13) flag++;
tmp2=(((date[6]-'0')*10+(date[7]-'0'))*10+(date[8]-'0'))*10+(date[9]-'0');
if(tmp2 > 2000) flag++;
}
return flag==3 ? 1 : 0;

}
  main()
  {
  char xx[20];
  gets(xx);
  printf("data valida %d?", valid(xx));
  }

-1

Hello

I made a small example of how to validate data using if() The user input, function, check date checks if the data is correct; I hope I’ve helped with an example

#include <stdio.h>

int main()
{
    int dd, mm, yy;

    printf("Enter date (DD/MM/YYYY format): ");
    scanf_s("%d/%d/%d", &dd, &mm, &yy);

    //check year
    if (yy >= 1900 && yy <= 9999)
    {
        //check month
        if (mm >= 1 && mm <= 12)
        {
            //check days
            if ((dd >= 1 && dd <= 31) && (mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12))
                printf("Date is valid.\n");
            else if ((dd >= 1 && dd <= 30) && (mm == 4 || mm == 6 || mm == 9 || mm == 11))
                printf("Date is valid.\n");
            else if ((dd >= 1 && dd <= 28) && (mm == 2))
                printf("Date is valid.\n");
            else if (dd == 29 && mm == 2 && (yy % 400 == 0 || (yy % 4 == 0 && yy % 100 != 0)))
                printf("Date is valid.\n");
            else
                printf("Day is invalid.\n");
        }
        else
        {
            printf("Month is not valid.\n");
        }
    }
    else
    {
        printf("Year is not valid.\n");
    }

    return 0;
} 
  • Hello, but where is the function ai ? Will I have to take this code and pass to the function then right ? And leave only the main user input. But I still need to check if the date contains bars.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.