title: Retrieve date format and parse if needed in PHP
body: <p>I've created this function when retrieving a date from database and echo in Italian format to screen:</p>
  
  <pre><code>function get_data_ita($date) {
      if ($date == "")
          return "";
  
      $d = new DateTime($date);
      return $d-&gt;format('d/m/Y');
  }
  </code></pre>
  
  <p>where <code>$date</code> is mysql format like: <code>2017-12-31 14:00:00</code></p>
  
  <p>Now, if I pass a correct format like: <code>2017-12-31 14:00:00</code> the function works.
  But sometimes I need to use the SAME function, passing an already formatted date like: <code>30/12/2017</code>. In this case, i get parsing error of course.</p>
  
  <p>How can I check if date passed is already in Italian format, and if yes return the untouched date, if not, parse the date?
  I need a function like:</p>
  
  <pre><code>function get_data_ita($date) {
      if ( $date== ALREADY_IN_ITALIAN_FORMAT )
         return $date;
  
      if ($date == "")
          return "";
  
      $d = new DateTime($date);
      return $d-&gt;format('d/m/Y');
  }
  
  echo get_data_ita("30/12/2017");
  echo get_data_ita("2017-12-31 14:00:00");
  </code></pre>
  
  <p>ECHO:</p>
  
  <pre><code>30/12/2017
  31/12/2017
  </code></pre>
  
  <p>UPDATE: I found solution myself:</p>
  
  <pre><code>function validateDate($date, $format = 'Y-m-d')
  {
      $d = DateTime::createFromFormat($format, $date);
      return $d &amp;&amp; $d-&gt;format($format) == $date;
  }
  
  function get_data_ita($datetime_db) {
  
      if ( validateDate($datetime_db, 'd/m/Y') ) {
          return $datetime_db;
      }
  
      if ($datetime_db == "")
          return "";
  
      $date = new DateTime($datetime_db);
      return $date-&gt;format('d/m/Y');
  
  }
  </code></pre>