php 将php日期时间存储在mysql数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13671185/
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-25 05:52:25  来源:igfitidea点击:

Store php datetime in mysql database

phpmysql

提问by Damian

I can't believe I can't do this, but I want to be able to store the current date and time from php in to a mysql table.

我不敢相信我不能这样做,但我希望能够将当前日期和时间从 php 存储到 mysql 表中。

The column in the table is type datetime. I've tried this

表中的列是日期时间类型。我试过这个

$current_date = date("Y-m-d");
$my_date = strtotime($current_date);
INSERT INTO my_table (date_time) VALUES ('$my_date')

but my timestamp comes up as 0000-00-00 00:00:00

但我的时间戳显示为 0000-00-00 00:00:00

This must be so easy to do but I just can't get it working! I want to use the timestamp from php rather than using the mysql now() function

这一定很容易做到,但我就是无法让它工作!我想使用来自 php 的时间戳,而不是使用 mysql now() 函数

采纳答案by chrki

Don't save it as the Unix Timestamp (which strtotime()outputs), but as "2012-12-02 13:00" into the DATETIME column.

不要将其保存为 Unix 时间戳(strtotime()输出),而是将其保存为“2012-12-02 13:00”到 DATETIME 列中。

回答by CoursesWeb

Try this:

尝试这个:

$my_date = date("Y-m-d H:i:s");
INSERT INTO my_table (date_time) VALUES ('$my_date');

In the date-format parameter of the date function, use :
'H' for 24hr format
'h' for 12hr format

在 date 函数的 date-format 参数中,使用:
'H' 表示 24 小时格式
'h' 表示 12 小时格式

回答by Abdullah

set the 'type' of column named 'date_time' as 'DATETIME' and run the following query:

将名为 'date_time' 的列的 'type' 设置为 'DATETIME' 并运行以下查询:

INSERT INTO my_table (`date_time`) VALUES (CURRENT_TIMESTAMP)

回答by NgaNguyenDuy

If you have the date in PHP as a timestamp, you can use the FROM_UNIXTIME function [1]

如果您将 PHP 中的日期作为时间戳,则可以使用 FROM_UNIXTIME 函数 [1]

mysql> insert into table_name values (FROM_UNIXTIME(your_timestamp_here));

Hope it helped

希望有帮助

[1]. https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime

[1]。https://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_from-unixtime

回答by fidazik

Remove the strtotime()

删除 strtotime()

$current_date = date("Y-m-d");
INSERT INTO my_table (date_time) VALUES ('$current_date')

If you want to include the hour, minutes and seconds, $current_date = date("Y-m-d H:i:s");

如果要包括小时、分钟和秒, $current_date = date("Ymd H:i:s");

回答by krastley

Create column type TIMESTAMP and set it to NOT NULL. Then pass in NULL during INSERT and MySQL will insert current date and time. This works for me.

创建列类型 TIMESTAMP 并将其设置为 NOT NULL。然后在 INSERT 期间传入 NULL,MySQL 将插入当前日期和时间。这对我有用。