0

I have an array formed from a string (2014/15):

$arr = explode("/", $Years, 2);

..and then two strings:

$frstHalfYear = $arr[0];
$secHalfYear = $arr[1];

..the output is following:

for $frstHalfYear: 2014
for $secHalfYear: 15

My question is : is it possible to convert 15 into a full year like 2014. This:

date("Y", strtotime($secHalfYear))

obviously is not working. The simple way would be to add 20at the start of the string, but I was wondering if there is some more generic way..

Thank you

Dims
  • 163
  • 1
  • 12

3 Answers3

5

Here's the most generic solution I can think of:

$secHalfYear = substr($frstHalfYear,0,-strlen($secHalfYear)).$secHalfYear;

Basically, this will take the 20 from 2014 and stick it before the 15 to make 2015.

It even supports 2099/100 format! But more importantly, you can write 2014/2015 and it will work just fine too.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

If you want something completely over the top: http://ideone.com/LzcgA3

var_dump(getDates('2014/15'));
var_dump(getDates('1999/12'));
var_dump(getDates('14/15'));


function getDates($dateRange) {
    $exp = explode('/', $dateRange);

    $startYear = $exp[0];
    // Cater for 14/15
    if ($startYear < 100) $startYear += date('Y') - date('y');

    $endYear = $exp[1];

    // If passed the full year, just use that
    if ($endYear < 100) {
        $shortStartYear = substr($startYear, 2, 2);
        if ($shortStartYear > $endYear) {
            // Jumping millenium
            $endYear += $startYear - $shortStartYear + 100;
        } else {
            // Same millenium
            $endYear += $startYear - $shortStartYear;
        }
    }

    return array('from'=>$startYear, 'to'=>$endYear);
}

This will actually cater for most dates. But appreciate if it's a little excessive ;)

PeteAUK
  • 968
  • 6
  • 16
-1
$secHalfYear = $frstHalfYear + 1;

You have to make certain assumptions to expand a date appropriately, but I don't believe I've ever seen this sort of year display when the second year didn't directly follow the first.

Jason
  • 13,606
  • 2
  • 29
  • 40