Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP convert 2 digit year to a 4 digit year

Tags:

date

php

I have data coming from the database in a 2 digit year format 13 I am looking to convert this to 2013 I tried the following code below...

$result = '13';

$year = date("Y", strtotime($result));

But it returned 1969

How can I fix this?

like image 989
user2327201 Avatar asked Jun 10 '13 18:06

user2327201


4 Answers

$dt = DateTime::createFromFormat('y', '13');
echo $dt->format('Y'); // output: 2013

69 will result in 2069. 70 will result in 1970. If you're ok with such a rule then leave as is, otherwise, prepend your own century data according to your own rule.

like image 187
webbiedave Avatar answered Nov 12 '22 14:11

webbiedave


One important piece of information you haven't included is: how do you think a 2-digit year should be converted to a 4-digit year?

For example, I'm guessing you believe 01/01/13 is in 2013. What about 01/01/23? Is that 2023? Or 1923? Or even 1623?

Most implementations will choose a 100-year period and assume the 2-digits refer to a year within that period.

Simplest example: year is in range 2000-2099.

// $shortyear is guaranteed to be in range 00-99
$year = 2000 + $shortyear;

What if we want a different range?

$baseyear = 1963; // range is 1963-2062
                  // this is, of course, years of Doctor Who!
$shortyear = 81;
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;

Try it out. This uses the modulo function (the bit with %) to calculate the offset from your base year.

like image 40
Chris Throup Avatar answered Nov 12 '22 13:11

Chris Throup


$result = '13';

$year = '20'.$result;

if($year > date('Y')) {
   $year = $year - 100;
}

//80 will be changed to 1980
//12 -> 2012
like image 11
Igor S. Avatar answered Nov 12 '22 14:11

Igor S.


Use the DateTime class, especially DateTime::createFromFormat(), for this:

$result = '13';
// parsing the year as year in YY format
$dt = DateTime::createFromFormat('y', $result);
// echo it in YYYY format
echo $dt->format('Y');
like image 3
hek2mgl Avatar answered Nov 12 '22 14:11

hek2mgl