用PHP重新格式化MySQL日期

时间:2016-09-24 01:27:50

标签: php mysql

我想从MySQL数据库中选择数据并将其显示在一个目前为止工作的表中,但我对日期格式有疑问。

我想将MySQL Date重新格式化为dd / mm / YY,但我不知道该怎么做,因为我没有专门选择日期列。我只是从表中选择所有列。

代码:

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Name</th><th>Date</th></tr>";

class TableRows extends RecursiveIteratorIterator { 
     function __construct($it) { 
         parent::__construct($it, self::LEAVES_ONLY); 
     }

     function current() {
         return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
     }

     function beginChildren() { 
         echo "<tr>"; 
     } 

     function endChildren() { 
         echo "</tr>" . "\n";
     } 
} 

$servername = "";
$username = "";
$password = "";
$dbname = "";

try {
     $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,     $password);
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $stmt = $conn->prepare("SELECT * FROM users"); 
     $stmt->execute();

     $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 

     foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
         echo $v;
     }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

2 个答案:

答案 0 :(得分:0)

是不是$ k是列名,$ v是值?

如果是,那么您可以轻松检测日期列值并对其进行格式化:

 foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
     switch ($k) {
          case 'date_column':
                // echo formatted $v
                break;
          default:
                echo $v;
                break;
     }
 }

答案 1 :(得分:-1)

以防我假设$k为列而$v为值是正确的,那么这应该有效:

 foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
 switch ($k) {
      case '{{column_name}}':
            // Format {{column_name}} as you like, e.g:
            $date_time = strtotime($v);
            print date("d-m-y", $date_time);
            break;
      default:
            echo $v;
            break;
 }
}