简体   繁体   English

如何在PHP中将日期时间转换为字符串?

[英]How to convert a date-time into string in PHP?

I have a date as follows. 我的日期如下。

$discount_start_date='03/27/2012 18:47';

$start_date=new DateTime($discount_start_date);
$start_date->format('Y/m/d H:i:s');

How can I convert it to a string in PHP so that it can be stored into MySql? 如何将它转换为PHP中的字符串,以便它可以存储到MySql中? I'm from Java background and very new to PHP. 我来自Java背景,对PHP很新。

Don't use DateTime . 不要使用DateTime The normal php way of doing this sort of thing is to use date() and strtotime() ; 执行此类操作的正常php方法是使用date()strtotime() ;

$discount_start_date = '03/27/2012 18:47';    
$start_date = date('Y-m-d H:i:s', strtotime($discount_start_date));

You don't actually need to convert it into a string. 您实际上不需要将其转换为字符串。 MySQL has a date, time, datetime, as well as timestamp native data types. MySQL具有日期,时间,日期时间以及时间戳本机数据类型。 You should be able to simply insert the date immediately without casting it to a string so long as you insert it into one of these fields and have it formatted properly. 您应该能够简单地插入日期而不将其强制转换为字符串,只要将其插入其中一个字段并正确格式化即可。

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

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