简体   繁体   中英

How to get last 3 months or weeks or years or days in PHP?

I have this working code that gets the last 30 days.

<?php
    echo date('Y-m-d').' - '.date('Y-m-d', strtotime('today - 30 days'));
?>

I wanted to also to make it more dynamic such as:

`date('Y-m-d', strtotime('from today to 3 months'));`
`date('Y-m-d', strtotime('from today to 7 weeks'));` 
`date('Y-m-d', strtotime('from today to 2 years'));` 
echo date('Y-m-d', strtotime('- 3 months')).'<br>';
echo date('Y-m-d', strtotime('- 7 weeks')).'<br>';
echo date('Y-m-d', strtotime('- 2 years'));

It's not necessary to specify today inside the strtotime() function.

To make it dynamic use variables , for example:

$amount = 5;
$field = 'months'; // or 'days' or 'years'...
echo date('Y-m-d', strtotime("- $amount $field")).'<br>';

Your current code looks just fine, but you can omit the 'today' part and just do:

date('Y-m-d', strtotime('-3 months'));
date('Y-m-d', strtotime('-7 weeks'));
date('Y-m-d', strtotime('-2 years'));

Please check this answer to get last dates from today :

<?php
  $today =  date('Y-m-d');
  echo $lastthereemonth = date('Y-m-d',strtotime('-3 month',strtotime($today))); echo "<br/>";
  echo $lastthereeweeks = date('Y-m-d',strtotime('-3 weeks',strtotime($today)));echo "<br/>";
  echo $lastthereedays = date('Y-m-d',strtotime('-3 day',strtotime($today)));
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM