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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago