php - 以日期时间格式mySQL插入当前日期
我在将日期正确插入数据库时遇到问题。
$date = date('m/d/Y h:i:s', time());
我使用这种格式,并且它正确地回声,但是,当我插入时
mysql_query("INSERT INTO table
(dateposted)
VALUES ('$date')");
它似乎无法正常工作,并且时间仍为00:00:00如果你能找到很棒的解决方案,谢谢。
CCates asked 2019-09-16T00:25:54Z
14个解决方案
191 votes
如果您想存储当前时间,只需使用MYSQL的功能。
mysql_query("INSERT INTO `table` (`dateposted`) VALUES (now())");
如果你需要使用PHP来做它,请将其格式化为Y-m-d H:i:s
$date = date('Y-m-d H:i:s');
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$date')");
Aaron W. answered 2019-09-16T00:26:14Z
33 votes
试试这个
$date = date('Y-m-d H:i:s');
Erik Giberti answered 2019-09-16T00:26:38Z
6 votes
NOW()用于在MySQL表中插入当前日期和时间。 数据类型为NOW()的所有字段都适用于此函数。
YYYY-MM-DD HH:mm:SS
示范:
以下代码显示了NOW()的用法
INSERT INTO auto_ins
(MySQL_Function, DateTime, Date, Time, Year, TimeStamp)
VALUES
(“NOW()”, NOW(), NOW(), NOW(), NOW(), NOW());
Gaurang answered 2019-09-16T00:27:21Z
4 votes
你可以使用CURRENT_TIMESTAMP,mysql函数
Diar Selimi answered 2019-09-16T00:27:45Z
3 votes
将名为dateposted的列的type设置为DATETIME并运行以下查询:
INSERT INTO table (`dateposted`) VALUES (CURRENT_TIMESTAMP)
Abdullah answered 2019-09-16T00:28:10Z
1 votes
“datetime”期望日期格式如下:YYYY-MM-DD HH:MM:SS
所以在插入时格式化您的日期。
Jan Hančič answered 2019-09-16T00:28:41Z
0 votes
$time=date("H:m");
$datetime=$date."T".$time;
mysql_query(INSERT INTO table (`dateposted`) VALUES ($datetime));
?>
PratapSingh hajari answered 2019-09-16T00:29:00Z
0 votes
我相信,您需要像下面的数据库字段类型一样更改您的代码。
mysql_query("INSERT INTO table (`dateposted`) VALUES ($datetime)");
希望,将完美地工作。
tisuchi answered 2019-09-16T00:29:31Z
0 votes
如果你从PHP传递日期,你可以使用任何格式使用STR_TO_DATE() mysql函数。让你通过html表格插入日期
$Tdate = "'".$_POST["Tdate"]."'" ; // 10/04/2016
$Tdate = "STR_TO_DATE(".$Tdate.", '%d/%m/%Y')" ;
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$Tdate')");
dateposted应为mysql date类型。 或者mysql会添加00:00:00
在某些情况下,您最好将日期和时间一起插入数据库,以便您可以使用小时和秒进行计算。 ()。
$Tdate=date('Y/m/d H:i:s') ; // this to get current date as text .
$Tdate = "STR_TO_DATE(".$Tdate.", '%d/%m/%Y %H:%i:%s')" ;
Salem answered 2019-09-16T00:30:10Z
0 votes
使其更容易和更有效的最佳方法是:
CREATE TABLE table_name (
field1,
..
..
time_updated timestamp default current_timestamp
)
现在,当您在表中插入一行时,可以跳过此字段(time_updated),因为它将填充当前时间作为默认值
Prakash GPz answered 2019-09-16T00:30:42Z
0 votes
只需使用您的时区:
date_default_timezone_set('Asia/Kolkata');
$date=date("Y/m/d h:i:sa");
xamDev answered 2019-09-16T00:31:08Z
-1 votes
用这个
type=varchar
接着在MYSQL中做
type=varchar
然后将成功插入日期和时间
vikas pandey answered 2019-09-16T00:31:55Z
-1 votes
$ date = date('Y-m-d H:i:s');与类型:'datetime'对我来说非常好,因为我想打印整个日期和时间戳..
$ date = date('Y-m-d H:i:s');$ stmtc-> bindParam(2,$日期);
Rehan answered 2019-09-16T00:32:28Z
-4 votes
试试这个
$('#datepicker2').datepicker('setDate', new Date('=$value->fecha_final?>'));
Cristhian Bonilla answered 2019-09-16T00:32:49Z