Check whether the verification date is valid in Linux

Source: Internet
Author: User

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/>}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.