How to get previous year using PHP
PhpPhp Problem Overview
How am I able to get the value of the previous year using PHP. Are there any predefined functions for it?
Php Solutions
Solution 1 - Php
try
echo date("Y",strtotime("-1 year"));
Solution 2 - Php
$year = date("Y");
$previousyear = $year -1;
Solution 3 - Php
There are many ways, you can either take away the amount of seconds in a year from time()
like so:
$prevYear = date('Y', time() - 60*60*24*365 );
Or if you'd prefer, use the PHPs clever strtotime()
function:
$prevYear = date('Y', strtotime('-1 year'));
Or even like others have said, if it's from todays year just do date('Y') -1
Solution 4 - Php
Shortest approach:
$lastYear = (int)date("Y") - 1;
Solution 5 - Php
function adddate($vardate,$added)
{
$data = explode("-", $vardate);
$date = new DateTime();
$date->setDate($data[0], $data[1], $data[2]);
$date->modify("".$added."");
$day= $date->format("Y-m-d");
return $day;
}
echo "Example : " . adddate("2010-08-01","-1 year");
Solution 6 - Php
If you want to display the entire date exactly 1 year ago, including the month and year:
<?php echo date("M d Y", strtotime("-1 year")); ?>
Solution 7 - Php
you can give a value of the input tag as :
<?php echo date("Y-m-d",strtotime("-1 year"));?>
Solution 8 - Php
Try This
date('Y', strtotime('last year'));
Solution 9 - Php
This thread needs an update.
Nowadays you would use the PHP date-time object and do something like this:
$lastYear = new DateTime();
$lastYear->sub(new DateInterval('P1Y'));
echo $lastYear->format('Y');
Solution 10 - Php
<?php
echo date("Y",strtotime("-1 year")); //last year "2021"
echo date("Y"); //current year "2022"
echo date("Y-m-d",strtotime("-1 year")); //one year ago "2021-03-31"
echo date("Y"); //current date "2022-03-31"
?>