Recently, an embedded protocol conversion software has been developed in C ++ in Linux. It has the time function and needs to verify the validity of the received date and time, and then set the date and time of the local machine. The validity check of the time is relatively simple, and the date is more complex. You need to consider the size of the month and the leap year.
My idea is: first perform a simple range check on the year, month, and day, then form a TM structure, and then call mktime to convert the TM into a time_t, during this process, mktime will automatically normalize invalid dates. For example, if the input is, the date will be converted to 2007-7-1. Therefore, if the year, month, and day before and after the conversion are the same, you can check whether the date is valid. For easier comparison, call localtime to convert time_t to TM for comparison. Verify the validity of the date based on the comparison result.
The Code is as follows:
Bool check_date (INT year, int month, int day) <br/>... {<br/> If (year <1900 | month <= 0 | month> 12 | day <= 0 | day> 31) <br/>... {<br/> return false; <br/>}</P> <p> // form time <br/> struct TM tm_new; <br/> tm_new.tm_year = year-1900; </P> <p> tm_new.tm_mon = month-1; <br/> tm_new.tm_mday = Day; </P> <p> tm_new.tm_hour = 0; </P> <p> tm_new.tm_min = 0; </P> <p> tm_new.tm_sec = 0; <br/> time _ T time_new = mktime (& tm_new); </P> <p> localtime_r (& time_new, & tm_new); <br/> If (tm_new.tm_year! = Year-1900 | tm_new.tm_mon! = Month-1 | tm_new.tm_mday! = Day) <br/>... {<br/> return false; <br/>}< br/> else <br/>... {<br/> return true; <br/>}< br/>}