0

Consider my method :

    static public function mysqldate($c,$f = 'd-M-y'){
      // date is supposed to be in dd/MMM/yyyy format.
      // returns a date in mysql form
      try {
        $result = "'" . DateTime::createFromFormat($f,$c)->format('Y-m-d') . "'";
      }
      catch (Exception $e){
        $error = "error in mysqldate <br />" ;
        $error .= "date passed : " . $c . "<br />";
        $error .= "error thrown : " . "<br />" . $e->getMessage() . "<br />";
        $error .= "trace : " . "<br />". $e->gettrace() . "<br />";;
        p0110error::terminal($error);            
      }
      return $result;
    }

It works fine when I pass it a valid date in d-M-y format like 17-mar-13. But when the date is not valid like say 17-ddd-13, it gives me a fatal error but the try catch is not triggered.

Why is that?

The error is "Fatal error: Call to a member function format() on a non-object in ..." (line 5).

Edited by PerplexedB: correction

2
Contributors
2
Replies
16
Views
4 Years
Discussion Span
Last Post by PerplexedB
1

gives me a fatal error but the try catch is not triggered.

Where does it say that it triggers an exception? createFromFormat just returns false on error. Since you just call a method on it without checking, it's just an error. PHP exceptions aren't embedded in all language features, as they are in C#.

Edited by pritaeas

0

That explains it. Thank you very much.

... and so as you cannot beat them, you join them, here is something that should work as expected:

    static public function mysqldate($c,$f = 'd-M-y'){
      // date is supposed to be in dd/MMM/yyyy format.
      // returns a date in mysql form
      try {
        $o = DateTime::createFromFormat($f,$c);
        if (!$o){
          throw new ErrorException("");
        }
        $result = "'" . $o->format('Y-m-d') . "'";
      }
      catch (Exception $e){
        $error = "error in mysqldate <br />" ;
        $error .= "date passed : " . $c . "<br />";        
        $error .= "format applied : " . $f . "<br />";
        p0110error::terminal($error);            
      }
      return $result;
    }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.