SimplePimple
SimplePimple

Reputation: 17

Parse a Y-m-d formatted date string into $year, $month, and $day variables

I have a string of 2011-03-06.

How do I extract the hyphen-separated values into individual variables:

$day = "06";
$month = "03";
$year = "2011";

Upvotes: 0

Views: 86

Answers (2)

Powerlord
Powerlord

Reputation: 88786

There are really two ways to do this. The first is with string manipulation, as shown by the other answers.

A better way of doing it would be to use PHP's date processing code:

$date = "2011-03-06";

$time = strtotime($date);
// or
$time_obj = DateTime::createFromFormat('Y-m-d', $date);

Then you can display $time however you want using the date command with $time as the second argument or DateTime's format command.

Upvotes: 1

Andrew Moore
Andrew Moore

Reputation: 95314

You can use explode() to separate the elements, and list() to assign them to three separate variables.

list($year, $month, $day) = explode('-', $date);

Upvotes: 2

Related Questions