Categories: Development

How to validate a date with PHP

A simple method to validate a date or check the date is true to the Gregorian calendar in PHP by defining the month, day and year.

PHP checkdate() will return true on a valid date and false when the date is not valid/doesn’t exist.

The parameters passed into the function are month, day and year as integers.

Examples

<?php
$year = 2021;
$month = 4;
$day = 30;


if (checkdate($month, $day, $year)) {
    echo "Valid date";
} else {
    echo "Not a valid date";
}

This will return ‘Valid date’

<?php
$year = 2021;
$month = 4;
$day = 31;


if (checkdate($month, $day, $year)) {
    echo "Valid date";
} else {
    echo "Not a valid date";
}

Returns ‘Not a valid date’ because April 2021 only has 30 days, there is no 31st.

Using this method is about matching to the Gregorian calendar rather than the date string format. Meaning you have to already have determined that your inputs are integers of their intended parameter.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago