将日期更改为时间戳,如sql

时间:2018-04-01 04:20:08

标签: php datetime

我想将日期格式更改为时间戳以保存在MySQL中。

现在我有一个数据'2018-03-31 20:07:56'。

$db_timestamp = '2018-03-31 20:07:56';

我可以使用strtotime函数来获取时间

$str_date = strtotime($db_timestamp)
date("m-d-Y", $str_date)

输出:03-31-2018

但现在我的问题是我将'03 -31-2018'作为我的初始数据。

$date = '03-31-2018'

我想回到'2018-03-31 00:00:00'作为结果。 请帮忙。感谢。

3 个答案:

答案 0 :(得分:2)

我们无法从仅包含年,月,日的字符串中获取时间值(20:07:56)。

无法从

获得
03-31-2018     

回到

2018-03-31 20:07:56

也许我们想要保留原始的小时,分​​钟,秒值或整个原始字符串。

答案 1 :(得分:0)

如果将日期保存为'2018-03-31 20:07:56'在数据库中。它将返回相同的值。

在日期功能中传递小时,分钟和秒。

$str_date = strtotime($db_timestamp);

$ str_date与'2018-03-31 20:07:56'

的值相同
date("Y-m-d H:i:s", $str_date);

我们可以在日期函数中传递H:i:s

<强>输出:

2018-03-31 20:07:56

答案 2 :(得分:0)

不要更改mysql中的基础数据。使用格式功能,如下所示。

首先,它将日期时间字符串转换为php中的Datetime对象,然后转换为所需的格式。从Datetime对象,您可以转换为任何其他格式。

$db_timestamp = '2018-03-31 20:07:56';
$mytime = DateTime::createFromFormat('Y-m-d H:i:s',$db_timestamp);
echo $mytime ->format('m-d-Y'); // shows  03-31-2018
echo $mytime ->format('d-m-Y'); // shows  31-03-2018
echo $mytime ->format('Y-m-d H:i:s'); // shows  2018-03-31 20:07:56