Reputation: 139
I have a field called "timestamp" in a database table which stores value in this format :- YYYY-MM-DD HH:MM:SS.
I would like to split apart and then fetch the date (YYYY-MM-DD) in a variable and also the time (HH:MM:SS) in another variable. Example:
$timestamp = "2012-10-19 18:19:56";
$get_date = "2012-10-19";
$get_time = "18:19:56";
I would be glad if anyone can help out with this using php.
Upvotes: 6
Views: 38385
Reputation: 11
If your timestamp format is "1 Jan 2018 15:00:01", with explode() the date will only return as '1. With DateTime is the perfect solution.
$timestamp = new DateTime("2011-08-04 15:00:01");
$date = $timestamp->format('Y-m-d');
$time = $timestamp->format('H:i:s');
Upvotes: 1
Reputation: 135
check this PHP fiddle:
http://phpfiddle.org/lite?code=%3C?php\n\n$datetime%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%20easily%20split%20the%20date%20into\n//%20year%20month%20and%20day\nlist($year,%20$month,%20$day)=explode(%27-%27,%20$date);\n\n?%3E\n
Upvotes: -1
Reputation: 19882
instead of exploding you can simply do it like this. This will help you for what ever format you have.
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));
Out put
2012-10-19 18:19:56
2012-10-19
18:19:56
Upvotes: 0
Reputation: 272396
You could use the explode
function; plus list
function could make your code slightly shorter:
list($get_date, $get_time) = explode(" ", "2012-10-19 18:19:56");
var_dump($get_date, $get_time);
Upvotes: 3
Reputation: 48006
You could simply split the string by the space character using PHP's explode()
function -
$timestamp = "2012-10-19 18:19:56";
$splitTimeStamp = explode(" ",$timestamp);
$date = $splitTimeStamp[0];
$time = $splitTimeStamp[1];
Another way of doing this would be this would be to use strtotime()
combined with date()
-
$date = date('Y-m-d',strtotime($timestamp));
$time = date('H:i:s',strtotime($timestamp));
Upvotes: 16
Reputation: 1107
Thats simple, use explode, try this below it wil work
$new_time = explode(" ",$timestamp);
$get_date = $new_time[0];
$get_time = $new_time[1];
Upvotes: 3
Reputation: 6147
$timestamp = "2012-10-19 18:19:56";
$splits = explode(" ",$timestamp);
$get_date = $splits[0];
$get_time = $splits[1];
Upvotes: 1