6

我在数据库表中有一个名为“时间戳”的字段,它以这种格式存储值:- YYYY-MM-DD HH:MM:SS。

我想分开然后在一个变量中获取日期(YYYY-MM-DD)以及另一个变量中的时间(HH:MM:SS)。例子:

$timestamp = "2012-10-19 18:19:56";
$get_date = "2012-10-19";
$get_time = "18:19:56";

如果有人可以使用 php 帮助解决这个问题,我会很高兴。

4

6 回答 6

16

explode()您可以使用 PHP 的函数简单地用空格字符分割字符串-

$timestamp = "2012-10-19 18:19:56";
$splitTimeStamp = explode(" ",$timestamp);
$date = $splitTimeStamp[0];
$time = $splitTimeStamp[1];

另一种方法是strtotime()结合使用date()-

$date = date('Y-m-d',strtotime($timestamp));
$time = date('H:i:s',strtotime($timestamp));
于 2013-01-22T11:13:43.070 回答
3

很简单,用explode,试试下面这个就行了

$new_time = explode(" ",$timestamp);
$get_date = $new_time[0];
$get_time = $new_time[1];
于 2013-01-22T11:13:24.797 回答
3

您可以使用该explode功能;pluslist函数可以使你的代码稍微短一些:

list($get_date, $get_time) = explode(" ", "2012-10-19 18:19:56");
var_dump($get_date, $get_time);
于 2013-01-22T11:16:00.033 回答
1
$timestamp = "2012-10-19 18:19:56";

$splits =  explode(" ",$timestamp);

$get_date = $splits[0];

$get_time = $splits[1];
于 2013-01-22T11:13:16.800 回答
0

而不是爆炸,你可以简单地这样做。这将对您拥有的任何格式有所帮助。

echo $timestamp = "2012-10-19 18:19:56";
echo '<br>';
echo $data = date('Y-m-d',strtotime($timestamp));
echo '<br>';
echo $time = date('H:i:s',strtotime($timestamp));

输出

2012-10-19 18:19:56
2012-10-19
18:19:56
于 2013-01-22T11:24:30.867 回答
0

检查这个 PHP 小提琴:

http://phpfiddle.org/lite?code=%3C?php \n\n$d​​atetime%20=%20%2228-1-2011%2014:32:55%22;\nlist($date,%20 $time)=explode(%27%20%27,%20$datetime);\n\n//%20check%20the%20result\necho%20%22date:%22.%20$date;\necho%20 %22%3Cbr%3Etime:%22.%20$time;\n\n//%20further%20more%20you%20can%20easy%20split%20the%20date%20into\n//%20year%20month%20and% 20day\nlist($year,%20$month,%20$day)=explode(%27-%27,%20$date);\n\n?%3E\n

于 2017-09-21T16:28:10.587 回答