Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - codeigniter - control date format

I have a form using which users can edit their own birthdate, i save the birthdates in the DB in this format 15/24/1989 which is dd/mm/yyyy

how can i check that the form birthday post value is formatted as shown?

also what if i pass 12/00/hello ?

i think i need numerics only and in a range of date 01 > dd < 31 , 01 > mm < 12 , 1920 > yyyy < current_year –


1 Answers

$date = date("d/m/Y", strtotime($this->input->post('date')));

To validate date in this format you should use this function.

function checkDateFormat($date) {
    if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $date)) {
        if(checkdate(substr($date, 3, 2), substr($date, 0, 2), substr($date, 6, 4)))
            return true;
        else
            return false;
    } else {
        return false;
    }
}

It will check the date format, as well as check the actual date itself with the PHP checkdate() function.

checkDateFormat("10/10/2010"); // true
checkDateFormat("29/02/2008"); // true
checkDateFormat("29/02/2007"); // false
checkDateFormat("10/10/20101"); // false
checkDateFormat("ilikecookie"); // false

etc.

like image 103
Sergey Telshevsky Avatar answered Mar 26 '26 23:03

Sergey Telshevsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!