Link to home
Start Free TrialLog in
Avatar of webcs
webcs

asked on

Parsing a date with PHP

Of course we all know we can get the system date from:

date("m-d-Y H:i:s");

However....assuming that I have a variable called $mydate with this data already in it, I need to seperate the data back out into its companents.

For example if we assume

$mydate equals  "2003-11-09 12:56:19"

I would like now to parse out that variable so I can get the year, month, day, hour, minute and second back.

thanks
Avatar of Michael701
Michael701
Flag of United States of America image

<?PHP
$mydate="2003-11-09 12:56:19";

echo 'strtotime()='.strtotime($mydate)."<br>\n";

$mydate_array = getdate(strtotime($mydate));

echo 'Year='.$mydate_array['year']."<br>\n";
echo 'Month='.$mydate_array['mon']."<br>\n";
echo 'Day='.$mydate_array['mday']."<br>\n";
?>

outputs

strtotime()=1068404179
Year=2003
Month=11
Day=9
Avatar of AlanJDM
AlanJDM

or...

<?PHP
$mydate="2003-11-09 12:56:19";
echo 'Year='.date("Y",strtotime($mydate))."<br>\n";
echo 'Month='.date("m",strtotime($mydate))."<br>\n";
echo 'Day='.date("d",strtotime($mydate))."<br>\n";
echo 'Hour='.date("g",strtotime($mydate))."<br>\n";
echo 'Month='.date("i",strtotime($mydate))."<br>\n";
echo 'Second='.date("s",strtotime($mydate))."<br>\n";
?>

outputs

Year=2003
Month=11
Day=09
Hour=12
Month=56
Second=19


Just another way to do it, does the same thing that Michael701 did.



Alan

ASKER CERTIFIED SOLUTION
Avatar of yahelb
yahelb

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of webcs

ASKER

Great answers...

Note to self, make sure to replace the g: with an H: when doing the parsing to get military time and not go nutty.

Looked for an hour for an error that wasn't there...figures :)