Jump to content

Change date from Y-m-d to m-d-Y with PHP


phpnewbfreak

Recommended Posts

So I have some data in a database that I want to write out with php. The problem is it spits it out as Year-Month-Day and I want it Month-Day-Year


 


So I wrote some code, but now it spits everything out as May 1, 1970. ??? It spits it out in the right order, but it's the wrong date (and the same date) for each entry. 



$result = mysql_query("SELECT * FROM `friend` ORDER BY bday") or die($myQuery."<br/><br/>".mysql_error());

$given = ['bday'];
$parseit = date("m-d-Y", strtotime($given));

while($row = mysql_fetch_array($result)){
$program = $row['ID'];
echo "<h2>" . $row['firstname'] . "</h2>";
echo "<h3>" . $parseit . "</h3>";
e
require_once("db_connx_close.php");
?>


$result = mysql_query("SELECT * FROM `friend` ORDER BY bday") or die($myQuery."<br/><br/>".mysql_error());

while($row = mysql_fetch_array($result)) {
  $program = $row['ID'];
  echo "<h2>" . $row['firstname'] . "</h2>";
  echo "<h3>" . date('m-d-Y', strtotime($row['bday'])) . "</h3>";
}

@Barand,

 

Wouldn't doing this in the query be more efficient? I always thought strtotime() was not a very speedy function.

 

 

$query = "SELECT ID, firstname, DATE_FORMAT(bday, '%m-%d-%Y') as bday FROM `friend` ORDER BY bday";
$result = mysql_query($query) or die($myQuery."<br/><br/>".mysql_error());

while($row = mysql_fetch_array($result)) {
  $program = $row['ID'];
  echo "<h2>{$row['firstname']}</h2>";
  echo "<h3>{$row['bday']}</h3>";
}

 

NOte: If you don't want leading zeros on the day and month use this for the format string in the query: %c-%e-%Y

To be honest I have never benchmarked it. But I wanted to show where OP's code should be calling the date() function and on which value.

 

Your code would also need a different alias other than "bday" or it won't sort correctly

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.