如何在 PHP 中将日期时间转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9879141/
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
How to convert a date-time into string in PHP?
提问by Bhavesh
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? I'm from Java background and very new to PHP.
如何将其转换为 PHP 中的字符串,以便将其存储到 MySql 中?我来自 Java 背景,对 PHP 非常陌生。
回答by Yada
Don't use DateTime
. The normal php way of doing this sort of thing is to use date()
and strtotime()
;
不要使用DateTime
. 做这种事情的正常 php 方法是使用date()
and strtotime()
;
$discount_start_date = '03/27/2012 18:47';
$start_date = date('Y-m-d H:i:s', strtotime($discount_start_date));
回答by Thomas Wright
You don't actually need to convert it into a string. MySQL has a date, time, datetime, as well as timestamp native data types. 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.
您实际上不需要将其转换为字符串。MySQL 具有日期、时间、日期时间以及时间戳本机数据类型。您应该能够立即简单地插入日期,而无需将其转换为字符串,只要将其插入这些字段之一并正确格式化即可。