How to Determine Whether a Date Is a Valid One in a C Program?

How to Determine Whether a Date Is a Valid One in a C Program? thumbnail
It is important to validate all input data in a C program.

Data validation is an important part of programming in any language. C programs accept data in specific formats in order to perform specific actions on that data. If a program is expecting a start date and an end date to calculate the total time, it is important that the program receive valid information. In this example, the start date should not be a later date than the end date, and both values need to be valid dates.

Instructions

    • 1

      Create a function to perform the validation within your C program. Declare a variable of type "DateTime" to hold a valid date. Declare another variable to hold the input date(s) as received from a file, a database or from user entry.

    • 2

      Call "DateTime.TryParse" passing the input date value and the datetime variable as an output parameter. If the function is successful, continue by executing the next line of code. If the function is not successful, either log or display an error to the user that the input date was not valid. This method is available in C#. If using an older version of C, you have a couple of different options.

    • 3

      Break down the input month, day and year into separate integers and attempt to create a new datetime variable from these values. A failure indicates that the input date value is invalid. This is one of the options available in C and C++.

    • 4

      Define an array to hold the number of days for each month in order. For example, January is position 1 and has 31 days. Therefore, myArray[1] would contain the number 31. The function should also determine if it is a leap year. Validating the year can be done by making sure the input value's first two digits are greater than "19" and the last two digits go from "00" to "99" and that the value is not greater than the current year. This is another option for ensuring that an invalid date is not accepted by the C program.

Related Searches:

References

  • Photo Credit Hemera Technologies/PhotoObjects.net/Getty Images

Comments

Related Ads

Featured