【问题标题】:Date manipulation issue日期操作问题
【发布时间】:2012-07-09 14:41:01
【问题描述】:

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

现在是 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)

知道我做错了什么吗?

【问题讨论】:

标签: php date strtotime


【解决方案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>";
?>

【讨论】:

    【解决方案2】:

    试试这个,(查看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);
    

    【讨论】:

    • 你只需要$now,如果它不同于“现在”。只是说:)
    【解决方案3】:

    试试这样的:

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

    【讨论】:

      【解决方案4】:

      似乎有点过大,您(和其他答案: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

      【讨论】:

        【解决方案5】:
        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)); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-06
          • 2011-03-12
          • 1970-01-01
          • 2012-01-28
          • 1970-01-01
          • 1970-01-01
          • 2014-10-10
          相关资源
          最近更新 更多