Date Format Change in Query

2019-03-06 23:42发布

问题:

I am using PHP JSON as API in android. I am taking news from MYSQL data with below code. Its working fine but date format is showing as YYYY-MM-DD. But I want get it like DD-MM-YYYY. I have searched lot of but not found any solution. Can anybody here can solve my issue ?

<?php
$response = array();
require 'db.php';

 $query = "SELECT * FROM news where order by id desc";
	

    $result = mysqli_query($conn,$query);
 
    if (mysqli_num_rows($result) > 0) {
        
    $response["news"] = array();
    
    while ($row = $result->fetch_assoc()) {
             
            $news= array();
            $news["id"] = $row["id"]; 
            $news["title"] = $row["title"];       
            $news["description"] = $row["description"];                
            $news["news_date"] = $row["news_date"]; 
          array_push($response["news"], $news);
          }
           $response["success"] = 1;

    // echoing JSON response
    //echo json_encode($response);
    echo json_encode($response['news']);
} else {

    $response["success"] = 0;
    echo json_encode($response);
}

Thank

回答1:

Change this line

   $news["news_date"] = date("d-m-Y" ,strtotime  ($row["news_date"]) ); 


回答2:

You can modify your SQL a bit to format the date to DD-MM-YYYY using date_format() like this:

select
    id,
    title,
    description,
    date_format(news_date,'%d-%m-%Y') news_date
from 
    news
order by
    id desc;


标签: php mysql mysqli