2012-07-10 69 views
0

我想获取上一个日历月的开始日期和结束日期。日期操作问题

因此,现在是2012年7月,我希望函数将2012年6月1日作为开始时间和2012年6月30日作为结束时间返回。

这是我的代码:

$current_month = date("Y-m-01 00:00:00"); 
$start_month = strtotime(date("Y-m-d", strtotime($current_month) . " -1 month")); 
$end_month = strtotime(date("Y-m-d", strtotime($current_month) . " -1 second")); 
echo "Start Month: " . date('Y-m-d',$start_month) . "(" . $start_month . ")<br>"; 
echo "End Month: " . date('Y-m-d',$end_month) . "(" . $end_month . ")<br>"; 

但回声的:

Start Month: 2012-07-01(1341093600) 
End Month: 2012-07-01(1341093600) 

任何想法,我做错了吗?

+0

检查这一点,它可以帮助你http://stackoverflow.com/questions/9735604/the-best-way-to-get-the-上个月的第一个和最后一个月 – Adi 2012-07-10 06:46:52

回答

1

回答什么是错与您发布的代码,你只需要在一点点移动你的轮托架和你有它。 :)

<?php 
$current_month = date("Y-m-01 00:00:00"); 
$start_month = strtotime(date("Y-m-d", strtotime($current_month . " -1 month"))); 
$end_month = strtotime(date("Y-m-d", strtotime($current_month . " -1 day"))); 
echo "Start Month: " . date('Y-m-d',$start_month) . "(" . $start_month . ")<br>"; 
echo "End Month: " . date('Y-m-d',$end_month) . "(" . $end_month . ")<br>"; 
?> 
0

试试这个,(检查strtotime手册)

$now = time(); 
$current_month = date("Y-m-01 00:00:00", $now); 
$start_month = strtotime("-1 month", $now); 
$end_month = strtotime("-1 second", $now); 
+0

只需要'$ now',如果它与“now”不同。只是说:) – KingCrunch 2012-07-10 07:06:00

0

尝试是这样的:

echo date("Y-m-d", mktime(0,0,0,date('m')-1,1,date('y'))); 
echo date("Y-m-d", mktime(0,0,0,date('m'),0,date('y'))); 
0

似乎有点过大,你(和其他的答案:X)什么尝试。它甫一

echo date('Y-m-d', strtotime('first day of last month')); 
echo date('Y-m-d', strtotime('last day of last month')); 

任意月

// 3 months in the past 
echo date('Y-m-d', strtotime('first day of -3 months')); 
echo date('Y-m-d', strtotime('last day of -3 months')); 

// 3 months in the future 
echo date('Y-m-d', strtotime('first day of +3 months')); 
echo date('Y-m-d', strtotime('last day of +3 months')); 

更多At the manual

0
echo $firstdate= "01/".date('m')."/".date('Y') ; 
$lastdateofmonth=date('t',date('m')); 
echo $lastdate=$lastdateofmonth."/".date('m')."/".date('Y') ; 

$date='2012-06-05 12:00:00'; 

echo "End = ".date("Y-m-t",strtotime($date)); 
echo "start = ".date("Y-m-01",strtotime($date));