我想将通过HTTP POST获得的时间字符串插入到带有时间戳字段的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是MYSQL中的时间戳数据类型。
发布于 2019-04-23 23:09:06
我建议使用Carbon库来处理日期格式,因为它使这些操作和其他操作变得非常容易。在这种情况下,我会这样做:
$carbonDate = new Carbon\Carbon('Apr 23, 2019 4:30:15 PM');
$timeStamp = $carbonDate->toDateTimeString();现在timeStamp是mysql的有效时间戳。
发布于 2019-04-23 23:41:44
使用PHP的DateTime将一种格式转换为另一种格式。你不需要任何依赖,比如Carbon -它对于你的用例来说是臃肿和过度杀伤力的。
您需要做的是告诉PHP输入日期格式是什么,以及您想要什么作为输出。
您的代码将"Apr 23, 2019 4:30:15 PM"声明为日期。在您的输入和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"不需要外部依赖,快速,简单,可读性好。
https://stackoverflow.com/questions/55813933
复制相似问题