【问题标题】:How to insert and read time/date in MySQL/PHP?如何在 MySQL/PHP 中插入和读取时间/日期?
【发布时间】:2011-08-05 15:28:22
【问题描述】:

我想以这种格式(使用 PHP)读取单日、月和年,而不添加 3 个额外的 MySQL 行:

day: 01
month: Jan, Feb, Mar..(first three letters)
year: 2011

这是我现在使用的表格和 PHP 脚本:

我用 PHP 添加日期:

mysql_query("INSERT INTO news (...,`time`) VALUES (...'".date(d.".".m.".".Y)."');"); 

我读出来的是:

$query = "SELECT * FROM news";
$result = mysql_query ($query);

while ($row = mysql_fetch_assoc ($result)) {
echo $row['time'];
}

MySQL 表:

news:
time(text):
"27.03.2011"

【问题讨论】:

  • 我很困惑,你为什么不只使用 MySQL 的一种内置日期/时间类型,比如日期?内部 MySQL 日期将是 Y-m-d,而不是 d.m.Y。此外,您错误地使用了date() - 日期代码在字符串中,因此(我不建议这样做,只是更正您的代码)它将是date('d.m.Y')。但没有理由这样做。

标签: php mysql date time


【解决方案1】:

查询应该是:

mysql_query("INSERT INTO news (...,`time`) VALUES (...'".date(d.".".M.".".Y)."');");

M 而不是 m 为您提供月份的 3 个字母文本表示。

获取它:

while ($row = mysql_fetch_assoc ($result)) {
    echo date( 'd', strtotime( str$row['time'] ) );
    echo date( 'M', strtotime( str$row['time'] ) );
    echo date( 'Y', strtotime( str$row['time'] ) );
}

阅读更多:

http://php.net/manual/en/function.date.php

【讨论】:

  • 感谢。那是我正在寻找的时间配置;)
【解决方案2】:

您可以在 PHP 中执行此操作,检查 strftime function 或在 SELECT 中使用类似

   SELECT DAY(date) as day, MONTH(date) as month, YEAR(date) as year FROM table

在 php 中,您可以将其作为 $result['day'] 访问。 $result['month'] 等 SELECT 查询中的“日期”当然是您存储日期的列的名称。我会推荐 strftime

【讨论】:

    【解决方案3】:

    你可以使用 MONTH(), DAY(), YEAR() Mysql函数。,即,

    SELECT MONTH(`time`) AS `month`, DAY(`time`) AS `day`, YEAR(`time`) AS `year` FROM `news` [...]
    

    【讨论】:

      【解决方案4】:
      SELECT *, substring(1,2) as day, substring(4,2) as month, substring(7) as year FROM table
      

      您也可以(并且应该)使用date 表格格式并使用DAY()MONTH()YEAR() 函数

      【讨论】:

        【解决方案5】:

        您应该在 mysql 表中使用 DATETIME 列。然后 MySQL 负责以自己的内部格式存储日期,您可以以任何您需要的格式检索它。

        要插入当前日期,您可以简单地

        INSERT INTO news (...,`time`) VALUES (...,NOW())
        

        要以您想要的格式检索它,请使用

        SELECT DATE_FORMAT(`time`, '%d.%b.%Y');
        

        Documentation on MySQL DATE_FORMAT()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-20
          • 2011-02-25
          • 1970-01-01
          • 2011-01-13
          相关资源
          最近更新 更多