Date field in Firefox and IE

-1

I have the following code:

$dataAssContrato = new DateTime($_POST['dataContrato']);

This line works perfectly in Chrome, but not in Firefox or IE, because when I try to register one each, I get the following warning:

  

Fatal error: Uncaught exception 'Exception' with message   'DateTime :: __ construct () [datetime .-- construct]: Failed to parse   time string (25/09/2014) at position 0 (2): Unexpected character '

     

Exception: DateTime :: __ construct () [datetime .-- construct]: Failed to parse   time string (25/09/2014) at position 0 (2): Unexpected character in

    
asked by anonymous 27.10.2014 / 13:36

3 answers

4

If the date comes from the form in the format d/m/Y convert it to the format of the database that is usually Y-m-d .

$dataAssContrato = DateTime::createFromFormat('d/m/Y', trim($_POST['dataContrato']));
$dataFormatada = $dataAssContrato->format('Y-m-d');
    
27.10.2014 / 14:04
1

The solution proposed by the lost seems to me ideal, but if you are having difficulty working the object, you can try a less orthodox solution, as follows:

list($d,$m,$y) = explode('/', $_POST['dataContrato']);
$dataAssContrato = new DateTime("$m/$d/$y");
    
27.10.2014 / 15:29
1

As @ lost already mentioned, it's easier to use the DateTime method: createFromFormat . I still suggest testing the date to make sure it has no errors, so the code would look like the @ lost's suggestion:

$dataAssContrato = DateTime::createFromFormat('d/m/Y', trim($_POST['dataContrato']));
if (!($dataAssContrato instanceof DateTime)) {
  die('Data Inválida!!'); /* Ou qualquer tratamento que achar necessário */
}
$dataFormatada = $dataAssContrato->format('Y-m-d');

I still emphasize that the browser has nothing to do with the code executed on the server side (php in this case). What is probably causing the problem is the formatting of the date fields. It is very likely that you are using an American Y-m-d format in Chrome / Chromium and a Brazilian d / m / Y format in Firefox and IE.

    
28.10.2014 / 11:12