简体   繁体   English

如何格式化输出日期的PHP

[英]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 . 当用户登录时,我的脚本只有一小段显示其成员资格的到期日期,但是它将输出显示为yyyy-mm-dd I am assuming this is because of how it is displayed in the sql table. 我假设这是因为它如何显示在sql表中。

<? 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 : date一起使用strtotime

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

If $row['Date'] is already a timestamp, then skip strtotime : 如果$row['Date']已经是一个时间戳,则跳过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. 这将以MdY格式显示日期。 If you want more details you can read the official PHP date documentation . 如果您想了解更多详细信息,可以阅读官方的PHP日期文档

You could change the SQL string using the date_format() MySQL function. 您可以使用date_format()MySQL函数更改SQL字符串。 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. 那应该为您带来日期作为格式化的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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