tags:

views:

3609

answers:

5

If I've got a date string:

$date = "08/20/2009";

And I want to separate each part of the date:

$m = "08";
$d = "20";
$y = "2009";

How would I do so?

Is there a special date function I should be using? Or something else?

Thanks!

+6  A: 

explode will do the trick for that:

$pieces = explode("/", $date);
$d = $pieces[1];
$m = $pieces[0];
$y = $pieces[2];

Alternatively, you could do it in one line (see comments - thanks Lucky):

list($m, $d, $y) = explode("/", $date);
Dominic Rodger
list($m,$d,$y) = explode("/", $date);
Lucky
@Lucky - thanks, edited in.
Dominic Rodger
+8  A: 

One way would be to do this:

$time = strtotime($date);
$m = date('m', $time);
$d = date('d', $time);
$y = date('Y', $time);
Doug Hays
ARGH! You beat me to it! lol
Daniel
Ah, but your response is more robust.
Doug Hays
Strtotime does not always work because of the timestamp constraint. Say you want to parse World War I, you cannot convert 28/08/1914 to a valid timestamp.
eyazici
+2  A: 

Is it always like that? Or will it be in any sort of file format?

Try strtotime.

Something like:

if(($iTime = strtotime($strDate))!==false)
{
 echo date('m', $iTime);
 echo date('d', $iTime);
 echo date('y', $iTime);
}
Daniel
A: 

Dominic's answer is good, but IF the date is ALWAYS in the same format you could use this:

$m = substr($date,0,2);
$d = substr($date,3,2);
$y = substr($date,-4);

and not have to use an array or explode

Bill H

Bill H
A: 

how about this:

list($m, $d, $y) = explode("/", $date);

A quick one liner.

Carson Myers