如何在PHP中将时间字符串转换为sql时间戳
我想将通过HTTPPOST获得的时间字符串插入到带有时间戳字段的mysql表中。我该怎么做 我的PHP代码是如何在PHP中将时间字符串转换为sql时间戳,php,mysql,sql,Php,Mysql,Sql,我想将通过HTTPPOST获得的时间字符串插入到带有时间戳字段的mysql表中。我该怎么做 我的PHP代码是 $time_string="Apr 23, 2019 4:30:15 PM"; $query = $database->prepare('INSERT INTO trips(trip_start) VALUES(?)') { $query->bind_param("s", $time_string]); $query->execute(); 这里trip_start是
$time_string="Apr 23, 2019 4:30:15 PM";
$query = $database->prepare('INSERT INTO trips(trip_start) VALUES(?)') {
$query->bind_param("s", $time_string]);
$query->execute();
这里trip_start是MYSQL中的一种时间戳数据类型,我建议使用library来处理日期格式,因为它使此操作和其他操作非常简单。在这种情况下,我会这样做:
$carbonDate = new Carbon\Carbon('Apr 23, 2019 4:30:15 PM');
$timeStamp = $carbonDate->toDateTimeString();
现在,时间戳
是mysql的有效时间戳。我建议使用库来处理日期格式,因为它使此操作和其他操作非常简单。在这种情况下,我会这样做:
$carbonDate = new Carbon\Carbon('Apr 23, 2019 4:30:15 PM');
$timeStamp = $carbonDate->toDateTimeString();
现在,时间戳
是mysql的有效时间戳。使用PHP从一种格式转换为另一种格式。您不需要任何依赖性,例如碳,这对于您的用例来说是膨胀和过度的
您需要告诉PHP输入日期格式是什么,以及您想要输出什么
您的代码规定日期为2019年4月23日下午4:30:15“。在您的输入和MySQL期望的内容之间转换的代码如下:
$date = 'Apr 23, 2019 4:30:15 PM';
$input_format = 'M d, Y H:i:s A'; // Apr 23, 2019 4:30:15 PM
$output_format = 'Y-m-d H:i:s' // 2019-04-23 16:30:15
$timezone = new \DateTimeZone("UTC"); // Make sure to correctly choose your time zone
$dt = \DateTime::createFromFormat($input_format, $date, $timezone);
echo $dt->format($output_format); // echoes "2019-04-23 16:30:15"
无需外部依赖,快速、简单且可读。使用PHP从一种格式转换为另一种格式。您不需要任何依赖性,例如碳,这对于您的用例来说是膨胀和过度的
您需要告诉PHP输入日期格式是什么,以及您想要输出什么
您的代码规定日期为2019年4月23日下午4:30:15“。在您的输入和MySQL期望的内容之间转换的代码如下:
$date = 'Apr 23, 2019 4:30:15 PM';
$input_format = 'M d, Y H:i:s A'; // Apr 23, 2019 4:30:15 PM
$output_format = 'Y-m-d H:i:s' // 2019-04-23 16:30:15
$timezone = new \DateTimeZone("UTC"); // Make sure to correctly choose your time zone
$dt = \DateTime::createFromFormat($input_format, $date, $timezone);
echo $dt->format($output_format); // echoes "2019-04-23 16:30:15"
不需要外部依赖项,快速、简单且可读。除了多个语法错误外,给定代码还有什么问题?除了多个语法错误外,给定代码有什么问题?可能重复