How do I convert to YYYY-mm-dd
and check if a date passed by a user via POST method is valid for my application?
How do I convert to YYYY-mm-dd
and check if a date passed by a user via POST method is valid for my application?
Previous method removed due to certain errors. Here's another way to validate Brazilian dates (not tested in other formats).
If you are in Brazil and still can not convert the date taken from your form to YYYY-mm-dd
, here are some lines of code that can help you:
$data = date('Y-m-d',strtotime(str_replace('/', '-', $data))); // converte datas em formato 'br' para sql.
If you are using dates in 'mm / dd / YYYY' format, you only need to invert 'm' and 'd' in the date
function.
To validate Brazilian dates you will need the following:
$date = strtotime(str_replace('/','-', $date));
Very simple, the strtotime
function will return FALSE
if it can not convert our date, which will be converted easily if it is valid.
str_replace
is used because when using bars /
PHP understands that we are working with the format mm/dd/YYYY
instead of dd/mm/YYYY
. When using hyphens PHP understands our date correctly. Such a function will convert the bars into hyphens that are present in string
$date
.
If you use dates in the format mm/dd/YYYY
you can use the following function to validate:
$date = human_to_unix(unix_to_human(strtotime($date), FALSE));
if($date==FALSE){
$this->form_validation->set_message('valid_date', 'Data inválida. Favor não inserir manualmente.');
return FALSE;
}else{
return TRUE;
}
Explanation: The algorithm will get the date value $data
passed to it in Y-m-d
format and will convert it to a date in unix
, which, if invalid will return, probably 0. This would already be enough for completely wrong dates as YY-dddd-mm
, but in order for the date to be fully filtered and validated I opted for one more conversion layer for "human" format YYYY-mm-dd
and then for unix
, which , attempting to convert an invalid date will return 0 (FALSE). After this we just checked if the date "survived" our tests and we have a return for a callback_function. :)