This question already has an answer here:
How can I get the value of a date in php? For example I have a date like this:
$date = "2013-01-29";
And what I want is to get the year the month and the day and assign it in a variable.
Example:
$year = "2013";
$month = "01";
$day = "29";
How can I do this?
</div>
Use strtotime(), which converts a string of various formats to a date. It can detect various formats of dates:
$date_unix = strtotime($date);
$year = date("Y", $date_unix);
$month = date("m", $date_unix);
$day = date("d", $date_unix);
Also see date() for a list of all modifiers.
Simple
$newdate=explode("-",$date);
$day=$newdate[2];
$month=$newdate[1];
$year=$newdate[0];
A more OOP way than @TobSpr would be using DateTime
$date = "2013-01-29";
$dt = new DateTime($date);
echo $dt->format('Y');
This have the advantage that we have full control over the date, we can even specify a specific timezone, handle poorly formatted input date strings (DateTime __construct will throw an exception on unparsable input)
$date = "2013-01-29 invalid";
try {
$dt = new DateTime($date);
echo $dt->format('Y');
} catch (Exception $e) {
printf('Failed to decode input date "%s", PHP said: %s', $date, $e->getMessage());
}
For information on what you can send into DateTime::format
, see date
$date = new DateTime('2013-01-29');
echo $date->format("Y");
echo $date->format("m");
echo $date->format("d");
in php you can do it in following way $date=" 2013-01-29"; $tem=explode("-",$date); $year=$tem[0]; $month=$temp[1]; $day=$temp[2];