Title:linux C Determines whether the date format is valid--2013-10-11 11:54
#include <string.h>//strlen (), strncpy () #include <ctype.h>//IsDigit () #include <stdlib.h>// Atoi () #include <stdio.h>/* valid format 2013-01-01 01:01:012013/11/11 11:11:11*/int main () {int isvaliddate (c Onst char* str) {//check date length const int len = 19;//valid format length is int len = strlen (str ); if (len = len) return 0; Check whether the year is in [1900, 2099] char year_str[5] = {0}; strncpy (Year_str, str, 4); int year = atoi (YEAR_STR); The year is converted to a number if (Years < 1900 | | 2099 < year) return 0; Check if the month and date are still time logical char month_str[3] = {0}, Day_str[3] = {0}, Hour_str[3] = {0}, Minute_str[3] = {0 }, Second_str[3] = {0}; strncpy (MONTH_STR, str + 5, 2); Extract the Month string strncpy (day_str, str + 8, 2); Extract Date string strncpy (hour_str, str + 11, 2); Extract the Hour string strncpy (minute_str, str + 14, 2); Extract minute string strncpy (second_str, str + 17, 2); Extract the second string int month = atoi (MONTH_STR); The month is converted to the number int day = atoi (DAY_STR); Date converted to numeric int hour = Atoi (HOUR_STR); Hours converted to digital int minute = atoi (MINUTE_STR); Minutes converted to digital int second = atoi (SECOND_STR); Seconds to Digital if (Hour > | | Hour < 0) | | (Minute > | | minute < 0) | | (Second > | | Second < 0)) Determines whether the hour, minute, or second is legal return 0; Switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:/*31 Day */ Return 0 < Day && Day < 32; Case 4:case 6:case 9:case 11:/*30 days */return 0 < day && Daily < 31; Case 2:/*2 month is special, leap year: 29 days, Common year: 28 days */{int leap = (0 == year% 4 && 0! = year% 100) | | (0 = = year% 400); return (1 = = Leap && (0 < Day && Day < 30)) | | (0 = = Leap && (0 < Day && Day < 29)); } Default:return 0; }} const char* str1 = "2013-10-10 24:10:10"; Const char* STR2 = "2014-12-01 23:60:23"; Const char* STR3 = "2013/02/31 01:11:53"; Const char* STR4 = "2100/11/11 01:11:11"; Const char* STR5 = "2013/11/11 01:11:11"; Const char* STR6 = "209905-9"; Const char* STR7 = "20000229"; printf (isvaliddate (str1)? "valid\n": "invalid\n"); printf (isvaliddate (str2)? "valid\n": "invalid\n"); printf (isvaliddate (STR3)? "valid\n": "invalid\n"); printf (isvaliddate (STR4)? "valid\n": "invalid\n"); printf (isvaliddate (STR5)? "valid\n": "invalid\n"); printf (isvaliddate (STR6)? "Valid\n": "invalid\n"); printf (isvaliddate (STR7)? "valid\n": "invalid\n"); }
Linux C Determines whether the date format is valid