Open In App

PHP checkdate() Function

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The checkdate() function in PHP is an important built-in function used to validate whether a given date is valid or not. It works by checking the values of month, day, and year, and returns true if the date is valid and false otherwise. This is particularly useful when you want to ensure a date is correct before performing operations with it.
 

Syntax:  

checkdate ( $month, $day, $year )


Parameters: The function accepts three mandatory parameters as shown above and described below:  

  1. $month: Specifies the month (must be between 1 and 12).
  2. $day: Specifies the day (must be within the valid range for the given month and year).
  3. $year: Specifies the year (must be in the range 1 to 32767).

Return Value:

  • true: If the date is valid.
  • false: If the date is invalid.

Examples:  

Input : $month = 12 $day = 31 $year = 2017
Output : true

Input : $month = 2 $day = 29 $year = 2016
Output : true 

Input : $month = 2 $day = 29 $year = 2017
Output : false


How it Handles Leap Years:

  • For February, in leap years (like 2016), checkdate() allows 29 days, while in non-leap years (like 2017), it only allows 28 days.

Examples of checkdate() Function

Below programs illustrate the checkdate() function in PHP :

Example 1: The program below check if the date is a valid one or not. 

php
<?php
// PHP program to demonstrate the checkdate() function 

$month = 12; 
$day = 31; 
$year = 2017; 

// returns a boolean value after validation of date 
var_dump(checkdate($month, $day, $year));

?> 

Output: 

bool(true)


Example 2: The program below check if the date is a valid one or not in case of a leap year and non-leap year.  

php
<?php
$month = 2; 
$day = 29; 
$year = 2016;  
var_dump(checkdate($month, $day, $year)); 
$month = 2; 
$day = 29; 
$year = 2017; 
var_dump(checkdate($month, $day, $year)); 
?> 

Output:  

bool(true)
bool(false)

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Next Article
Article Tags :

Similar Reads