2014-06-30 79 views

回答

0
$date = date('F',strtotime($startDate)); 

对于全月表示(即Januaray,日等)

$date = date('M',strtotime($startDate)); 

对于缩写......(即一月,二月,三月)

REFERENCE

如果您想要根据两个日期来回应那些月份。

$d = "2014-03-01"; 
$startDate = new DateTime($d); 
$endDate = new DateTime("2014-05-01"); 

function diffInMonths(DateTime $date1, DateTime $date2) 
{ 
    $diff = $date1->diff($date2); 
    $months = $diff->y * 12 + $diff->m + $diff->d/30; 
    return (int) round($months); 
} 

    $t = diffInMonths($startDate, $endDate); 

    for($i=0;$i<$t+1;$i++){ 
    echo date('F',strtotime($d. '+'.$i.' Months')); 
    } 

PHP SANDBOX EXAMPLE

1

一个快速的解决方案是,每天分析和检查月份:

$startDate = "2014-03-01"; 
$endDate = "2014-05-25"; 

$start = strtotime($startDate); 
$end = strtotime($endDate); 

$result = array(); 
while ($start <= $end) 
{ 
    $month = date("M", $start); 

    if(!in_array($month, $result)) 
     $result[] = $month; 

    $start += 86400; 
} 

print_r($result); 

我相信这是可以做到多少有效的新的OOP(DateTime对象)的方式,但是这是速度快,如果您需要使其工作,则无需大脑。

+0

感谢这有助于。 –

5

为此PHP提供了DatePeriod对象。看看下面的例子。

$period = new DatePeriod(
    new DateTime('2014-03-01'), 
    DateInterval::createFromDateString('1 month'), 
    new DateTime('2014-05-25') 
); 

foreach ($period as $month) { 
    echo strftime('%B', $month->format('U')); 
} 
+0

最佳答案....就在这里:) – KyleK

+0

我不明白为什么人们总是喜欢复杂而难以理解的解决方案。新来PHP的人会沉迷于面向对象的方式比摇滚更快。 –

+0

@ rm-rf OOP让你的生活变得更轻松,问题变得越复杂,使用面向对象的解决就越容易。所以请永远不要使用面向对象的建议,当涉及初学者时更多 – giorgio

0
<?php 
$startDate = "2014-03-01"; 
echo date('F',strtotime($startDate)); 
? 
+1

请解释而不是张贴您的代码。我们在这里教人们要做的更好。给一个人一条鱼... – DavidG

相关问题