简体   繁体   中英

How to format output date php

I have a small piece of my script when a user logs in that shows their membership expiration date, however it displays the output as yyyy-mm-dd . I am assuming this is because of how it is displayed in the sql table.

<? echo "Welcome, {$_SESSION['username']}"; ?><p>
<?php

// Make a MySQL Connection
mysql_connect("server", "db", "db") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

$query =  "SELECT `Date` FROM `USERS` WHERE `username` = '" . $_SESSION['username'] . "'";
// Retrieve all the data from the "example" table
$result = mysql_query($query) or die(mysql_error())
or die(mysql_error());

// store the record of the "example" table into $row
$row = mysql_fetch_array( $result );

echo "Membership Expiration Date: ".$row['Date'];
?>

I have tried putting format commands in

".$row['Date'];

such as

".$row['Date , M d, Y'];
".$row['Date , M-d-Y'];

However I am sure that is wrong. I'm reading date formats and conversions however if I need to convert it, I am not sure where to input it. If it needs to be defined before the echo, or if I'm missing something in the

".$row['Date'];

Still trying, however any help would be appreciated, thank you.

Use strtotime along with date :

echo "Membership Expiration Date: ". date("Y-m-d", strtotime($row['Date']));

If $row['Date'] is already a timestamp, then skip strtotime :

echo "Membership Expiration Date: ". date("Y-m-d", $row['Date']);

For more help, check all the similar questions asked on the column to your right --------------------------->>

What you will want to do is use the date functions. Here is how you will manipulate your date:

echo date('Y-m-d', strtotime($row['Date']));

This will display a date to the MdY format. If you want more details you can read the official PHP date documentation .

You could change the SQL string using the date_format() MySQL function. It should something like this:

SELECT DATE_FORMAT(`Date`, ''%m/%d/%y'') AS Date FROM `USERS` WHERE `username` = '

That should bring you the date as a formatted string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM