-2

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?

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
rochellecanale
  • 205
  • 2
  • 8
  • 21

5 Answers5

4

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

hank
  • 3,748
  • 1
  • 24
  • 37
1
$date = new DateTime('2013-01-29');
echo $date->format("Y");
echo $date->format("m");
echo $date->format("d");
Dezigo
  • 3,220
  • 3
  • 31
  • 39
0

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.

tobspr
  • 8,200
  • 5
  • 33
  • 46
-2

Simple

$newdate=explode("-",$date);
$day=$newdate[2];
$month=$newdate[1];
$year=$newdate[0];
ABorty
  • 2,512
  • 1
  • 13
  • 16
-2

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];

alok.kumar
  • 380
  • 3
  • 11