在给定扩展日期字符串的PHP中,如何以长格式提取月份年份?

时间:2010-04-13 20:54:50

标签: php datetime strtotime

我的尝试解决方案是:

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

预期结果应为:“2009年11月”

还有其他简单的解决方案吗?

2 个答案:

答案 0 :(得分:2)

虽然正则表达式可以做到这一点,但您可以更容易理解

$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));

答案 1 :(得分:1)

date_default_timezone_set  ('Etc/GMT-6');
$unixtime = strtotime($date_bad);
$date = date("F Y",$unixtime);
echo $date;

Time Zones