views:

52

answers:

2

My attempted solution was:

$date = "Nov 30 2009 03:00:00:000PM";
echo date("F Y", strtotime($date));

Expected result should be: "November 2009"

Any other simple solutions?

+2  A: 

While a regex could do it, here's something you might understand easier

$date_bad = "Nov 30 2009 03:00:00:000PM";

$piece_date = array();
$piece_date = explode(' ', $date_bad);
$date_good = $piece_date[0] .' '. $piece_date[1] .', '. $piece_date[2] .' ';

$piece_time = array();
$piece_time = explode(':', $piece_date[3]);

// check if the last part contains PM
if ( is_numeric(strpos($piece_time[3], 'PM')) )
{
    $ampm = 'PM';
}
// check if the last part contains AM
elseif ( is_numeric(strpos($piece_time[3], 'AM')) )
{
    $ampm = 'AM';
}
// no AM or PM is there, so it's a 24hr string
else
{
    $ampm = ''; 
}

$date_good .= $piece_time[0] .':'. $piece_time[1] .':'. $piece_time[2] . $ampm;

echo date("F", strtotime($date_good));
TravisO
+1  A: 
date_default_timezone_set  ('Etc/GMT-6');
$unixtime = strtotime($date_bad);
$date = date("F Y",$unixtime);
echo $date;

Time Zones

Brant
Can't get simpler than strtotime!
Brant
The question's example already used strtotime() and it wasn't working.
TravisO