如何使用 PHP 为 MySQL DATETIME 类型生成日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9490177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:56:45  来源:igfitidea点击:

How to generate date for MySQL DATETIME type with PHP?

phpmysqldatetime

提问by JohnUS

I need to get the records which are inserted in last 24 hours. I have read about it and got that I need to use DATETIMEtype in my MySQL date column.
But my problem is I don't know how to generate date for MySQL DATETIMEtype with PHP ?
How can I do this? Thanks in advance.

我需要获取过去 24 小时内插入的记录。我已经阅读了它并且知道我需要DATETIME在我的 MySQL 日期列中使用类型。
但我的问题是我不知道如何DATETIME使用 PHP为 MySQL类型生成日期 ?
我怎样才能做到这一点?提前致谢。

回答by apelliciari

Simply

简单地

$mysql_date_now = date("Y-m-d H:i:s");

Because DATETIMEin mysql is YYYY-MM-DD HH:ii:ss

因为DATETIME在 mysql 中是YYYY-MM-DD HH:ii:ss

回答by bretterer

If you are looking just for a way to generate the datetime to insert into the datetime field just use the following code

如果您只是在寻找一种生成日期时间以插入日期时间字段的方法,请使用以下代码

$datetime = date('Y-m-d H:i:s') ;

or for the direct sql

或直接 sql

INSERT INTO {TABLE} ({DATETIME}) VALUES (NOW())

This will create a date that looks like

这将创建一个看起来像的日期

2012-02-28 16:44:25

If you are looking for the query to get the last 24 hours use

如果您正在寻找获取过去 24 小时使用情况的查询

SELECT * FROM tablename WHERE date_field > NOW() - interval 1 day

回答by Eugen Rieck

There are two ways to go:

有两种方法:

  1. Use a textual representation - something like:

    <?php
        $year=2012; $month=2; $day=27;
        $hour=22; $minute=44; $second=58;
    
        $sql="SELECT something FROM something WHERE datecolumn>='$year-$month-$day $hour:$minute:$second'";
    ?>
    
  2. Do this directly in SQL

    SELECT something FROM something WHERE datecolumn >= DATE_SUB(NOW(), INTERVAL 1 DAY);
    
  1. 使用文本表示 - 类似于:

    <?php
        $year=2012; $month=2; $day=27;
        $hour=22; $minute=44; $second=58;
    
        $sql="SELECT something FROM something WHERE datecolumn>='$year-$month-$day $hour:$minute:$second'";
    ?>
    
  2. 直接在 SQL 中执行此操作

    SELECT something FROM something WHERE datecolumn >= DATE_SUB(NOW(), INTERVAL 1 DAY);
    

回答by John Fischer

I would change the MySQL database to do half the work, unless you do not like the time on the server. Name: dateSomething Type: TIMESTAMP Default: CURRENT_TIMESTAMP

我会改变 MySQL 数据库来做一半的工作,除非你不喜欢服务器上的时间。名称:dateSomething 类型:TIMESTAMP 默认值:CURRENT_TIMESTAMP

And then the SQL code

然后是SQL代码

INSERT INTO {TABLE} ({dateSomething}) VALUES (DEFAULT)