1
How do I convert to YYYY-mm-dd
and check if a date transmitted by a user via POST method is valid for my application?
1
How do I convert to YYYY-mm-dd
and check if a date transmitted by a user via POST method is valid for my application?
2
Previous method removed due to certain errors. Here is another way to validate dates brazilian (not tested in other formats).
If you’re in the Brazil and still could 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' passed in the function date
.
To validate dates brazilian you will need the following:
$date = strtotime(str_replace('/','-', $date));
Very simple, the function strtotime
will return FALSE
if you cannot 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 hyphens that are present in string
$date
.
If you use dates in format mm/dd/YYYY
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 take the date value $data
passed to him in the format Y-m-d
and will convert it into a date on unix
, which, if invalid will probably return 0. This would already suffice for completely wrong dates like YY-dddd-mm
, but for the date to be fully filtered and validated I opted for another layer of conversion to "human format" YYYY-mm-dd
and then to unix
, which, when trying to convert an invalid date will return 0 (FALSE). After this it is only verified if the date "survived" our tests and we have a return for a callback_Function. :)
Browser other questions tagged database codeigniter form date formatting
You are not signed in. Login or sign up in order to post.