PHP - codeigniter - control date format

user895171 picture user895171 · Sep 19, 2012 · Viewed 7.3k times · Source

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 –

Answer

Sergey Telshevsky picture Sergey Telshevsky · Sep 19, 2012
$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.