Tech Tip: Using PHP to check a date for validity
PRODUCT: 4D | VERSION: 13.5 | PLATFORM: Mac & Win
Published On: February 17, 2015
This Tech Tip is an implementation of the php function 'checkdate' which is used to validate a Gregorian date. The 'checkdate' function checks the validity of the date formed by the arguments and considers a date valid if each parameter is properly defined and within their expected range taking leap years into consideration.
The general syntax for the PHP function is:
bool checkdate ( int $month , int $day , int $year ) |
Each of the parameters for the 'checkdate' function are integer values while the return value of the function is a boolean.
Parameters:
- $month (integer value)
- The month is between 1 and 12 inclusive.
- $day (integer value)
- The day is within the allowed number of days for the given month. Leap years are taken into consideration.
- $year (integer value)
- The year is between 1 and 32767 inclusive.
Return:
- Boolean
- Returns TRUE if the date given is valid; otherwise returns FALSE.
Using the 'checkdate' function from 4D with the PHP Execute command.
The following method demonstrates an implementation of the PHP function 'checkdate' using the PHP Execute 4D command:
// php_checkdate // C_DATE($1) := 4D Date Var // C_BOOLEAN($0) := returns True if valid Gregorian date // Usage: $valid_b:=php_checkdate(!11/31/2011!) C_DATE($1;$date_d) C_INTEGER($month;$day;$year) C_BOOLEAN($0;$output;$phpOK) If (Count parameters=1) $date_d:=$1 $month:=Month of($date_d) $day:=Day of($date_d) $year:=Year of($date_d) $phpOK:=PHP Execute("";"checkdate";$output;$month;$day;$year) $0:=$output Else // no input date given so it cannot be valid $0:=False End if |
If the method above is saved in your database as a project method named php_checkdate then it can be used like this:
Example 1:
// use case #1 C_BOOLEAN($bool) C_DATE($date) $date:=!00/00/0000! $bool:=php_checkdate ($date) ALERT("is "+String($date)+" valid?\r\n"+String($bool)) |
Example 2:
// use case #2 C_BOOLEAN($bool) C_DATE($date) $date:=!02/02/2002! $bool:=php_checkdate ($date) ALERT("is "+String($date)+" valid?\r\n"+String($bool)) |
Example 3:
// making some assertions first to confirm it is working ASSERT(php_checkdate (!01/01/2001!);"01/01/01 is a valid date") ASSERT(php_checkdate (!12/31/2011!);"12/31/11 is a valid date") ASSERT(Not(php_checkdate (!00/00/0000!));"0/0/0 is NOT a valid date") |