Date minus 1 year?

前端 未结 8 1837
时光取名叫无心
时光取名叫无心 2020-11-27 14:28

I\'ve got a date in this format:

2009-01-01

How do I return the same date but 1 year earlier?

相关标签:
8条回答
  • 2020-11-27 14:48

    Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php

    So, for reference, you can also use a \DateInterval to modify a \Datetime object:

    $date = new \DateTime('2009-01-01');
    $date->sub(new \DateInterval('P1Y'));
    
    echo $date->format('Y-m-d');
    

    Which returns:

    2008-01-01
    

    For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php

    0 讨论(0)
  • 2020-11-27 14:52

    You can use strtotime:

    $date = strtotime('2010-01-01 -1 year');
    

    The strtotime function returns a unix timestamp, to get a formatted string you can use date:

    echo date('Y-m-d', $date); // echoes '2009-01-01'
    
    0 讨论(0)
  • 2020-11-27 14:55

    Use strtotime() function:

      $time = strtotime("-1 year", time());
      $date = date("Y-m-d", $time);
    
    0 讨论(0)
  • 2020-11-27 14:59

    You can use the following function to subtract 1 or any years from a date.

     function yearstodate($years) {
    
            $now = date("Y-m-d");
            $now = explode('-', $now);
            $year = $now[0];
            $month   = $now[1];
            $day  = $now[2];
            $converted_year = $year - $years;
            echo $now = $converted_year."-".$month."-".$day;
    
        }
    
    $number_to_subtract = "1";
    echo yearstodate($number_to_subtract);
    

    And looking at above examples you can also use the following

    $user_age_min = "-"."1";
    echo date('Y-m-d', strtotime($user_age_min.'year'));
    
    0 讨论(0)
  • 2020-11-27 15:05
    // set your date here
    $mydate = "2009-01-01";
    
    /* strtotime accepts two parameters.
    The first parameter tells what it should compute.
    The second parameter defines what source date it should use. */
    $lastyear = strtotime("-1 year", strtotime($mydate));
    
    // format and display the computed date
    echo date("Y-m-d", $lastyear);
    
    0 讨论(0)
  • 2020-11-27 15:07

    an easiest way which i used and worked well

    date('Y-m-d', strtotime('-1 year'));
    

    this worked perfect.. hope this will help someone else too.. :)

    0 讨论(0)
提交回复
热议问题