I'm currently building a room booking system and was wondering how to check if the user has entered a date (get value) in the correct UK format of dd/mm/yyyy.
$uk_date = $_GET["date"];
For example to avoid a situation where the user types in 12/2012 or 2012 or uses the incorrect separators.
Thanks in advance!
The best would be DateTime::createFromFormat
:
$date = DateTime::createFromFormat('d/m/Y', $uk_date);
$errors = DateTime::getLastErrors();
if($errors['warning_count'] || $errors['error_count']) {
// something went wrong, you can look into $errors to see what exactly
}
If the parsing is successful then you have in your hands a DateTime
object that provides lots of useful functions. One of the most important is DateTime::format
which will let you get data out of the object, e.g.:
$year = $date->format('Y');
Use a regex code like this:
$str = '12/12/2012';
$regex = '#^\d{1,2}([/-])\d{1,2}\1\d{4}$#';
if (preg_match($regex, $str, $m))
echo "valid date\n";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With