How to get previous month and year relative to today, using strtotime and date?

前端 未结 15 968
情书的邮戳
情书的邮戳 2020-11-28 07:48

I need to get previous month and year, relative to current date.

However, see following example.

// Today is 2011-03-30
echo date(\'Y-m-d\', strtotim         


        
15条回答
  •  暖寄归人
    2020-11-28 08:32

    Perhaps slightly more long winded than you want, but i've used more code than maybe nescessary in order for it to be more readable.

    That said, it comes out with the same result as you are getting - what is it you want/expect it to come out with?

    //Today is whenever I want it to be.
    $today = mktime(0,0,0,3,31,2011);
    
    $hour   = date("H",$today);
    $minute = date("i",$today);
    $second = date("s",$today);
    $month  = date("m",$today);
    $day    = date("d",$today);
    $year   = date("Y",$today);
    
    echo "Today: ".date('Y-m-d', $today)."
    "; echo "Recalulated: ".date("Y-m-d",mktime($hour,$minute,$second,$month-1,$day,$year));

    If you just want the month and year, then just set the day to be '01' rather than taking 'todays' day:

     $day = 1;
    

    That should give you what you need. You can just set the hour, minute and second to zero as well as you aren't interested in using those.

     date("Y-m",mktime(0,0,0,$month-1,1,$year);
    

    Cuts it down quite a bit ;-)

提交回复
热议问题