Renish Khunt Renish Khunt - 1 month ago 14
PHP Question

PHP get small year from 2015?

Hello friends i Want to getting small year from full year like

$smallYear = date('y',strtotime('2016'));
// it's return 16

// when i passed 2017
$smallYear = date('y',strtotime('2017'));
// it's return 16 means it's return current date


How to get 16 from 2016 and 17 from 2017 using php. below is my full function for generating years.

public static function getYears() {
$years = array();
$curYear = date("Y");
$limit = 16;
echo date('y',strtotime('2015'));
for ($x = $curYear; $x < $curYear + $limit; $x++) {
$xd = date('y',strtotime($x));
$years[$xd] = $x;
}
return $years;
}


I want to set small year as a key. i want output like

array(
'16' => 2016,
'17' => 2017,
'18' => 2018,
'19' => 2019
)


Thanks

Answer
<?php
function makeShortYear($theYear) {
   return date('y',strtotime("$theYear-01-01"));
}

echo makeShortYear(2016) . "\n";  // 16
echo makeShortYear(2017) . "\n";  // 17
echo makeShortYear(1998) . "\n";  // 98
?>

You did not state your requirements very clearly (two example inputs is not enough to build a full picture of how you wish your program to behave in general), but is this what you meant?

The year 3000 won't work, because strtotime is based on 32-bit UNIX timestamps, which don't go that far.

Here's an alternative which does:

<?php
function makeShortYear($theYear) {
   return (new DateTime("$theYear-01-01"))->format("y");
}

echo makeShortYear(2016) . "\n";  // 16
echo makeShortYear(2017) . "\n";  // 17
echo makeShortYear(1998) . "\n";  // 98
echo makeShortYear(3000) . "\n";  // 00
echo makeShortYear(3001) . "\n";  // 01
?>

In both cases, the key is very simply to provide a full date as input, by adding arbitrary month and day.