Reputation: 2143
I have string with following format:
$date = "2012-07-22 17:48:24";
I want to get the year, month and date in the variables and ignore the time. I am trying following:
list($year, $month, $day) = split('[-]', $date);
This returns correct values to $year
and $month
, but the $day
gets: "22 17:48:24"
, while I want to get only 22.
Upvotes: 0
Views: 1387
Reputation: 51970
There's also the sscanf()
function.
sscanf('2012-07-22 17:48:24', '%d-%d-%d', $year, $month, $day);
Upvotes: 4
Reputation: 14438
Use explode:
$date = "2012-07-22 17:48:24";
$date = explode(" ", $date);
list($year, $month, $day) = split('[-]', $date[0]);
EDIT:
You should use explode for the date too:
list($year, $month, $day) = explode('-', $date[0]);
The use of split is discouraged as it was deprecated.
Upvotes: 3
Reputation: 2232
$date = date('Y-m-d', strtoime("2012-07-22 17:48:24"));
list($year, $month, $day) = split('[-]', $date);
Upvotes: 1
Reputation: 72729
Instead of exploding the value you could use a DateTime object:
<?php
$date = "2012-07-22 17:48:24";
$dateTime = new DateTime($date);
var_dump(array(
'year' => $dateTime->format('Y'),
'month' => $dateTime->format('m'),
'day' => $dateTime->format('d'),
));
This would be the most flexible option imho.
As @zerkms noted in his comment you could also use strtotime()
and date()
, but I find myself only using the DateTime
class lately. Not only because it has a nice OO API, but also because it will keep on working after the year 2038 :-). The comment is not wrong though.
Upvotes: 12
Reputation: 43582
$date = "2012-07-22 17:48:24";
preg_match('~^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$~', $date, $m);
print_r($m);
Upvotes: 1