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).

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#.

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;
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.