PHP将2位数年份转换为4位数年份

use*_*201 15 php date

我有来自数据库的数据以2位数年份格式13我希望将其转换为2013我尝试下面的代码...

$result = '13';

$year = date("Y", strtotime($result));
Run Code Online (Sandbox Code Playgroud)

但它在1969年回归

我怎样才能解决这个问题?

web*_*ave 24

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

69会导致2069.70会导致1970.如果您对这样的规则没问题,那么请保持原样,否则,根据您自己的规则添加您自己的世纪数据.


Chr*_*oup 12

您未包含的一条重要信息是:您认为如何将2位数年份转换为4位数年份?

例如,我猜你相信01/01/13是在2013年.01/01/23怎么样?那是2023年吗?还是1923年?甚至1623年?

大多数实施将选择100年期间并假设2位数表示该期间内的一年.

最简单的例子:年份在2000-2099范围内.

// $shortyear is guaranteed to be in range 00-99
$year = 2000 + $shortyear;
Run Code Online (Sandbox Code Playgroud)

如果我们想要不同的范围怎么办?

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

试试看.这使用模数函数(带有%的位)来计算基准年的偏移量.


Igo*_* S. 7

$result = '13';

$year = '20'.$result;

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

//80 will be changed to 1980
//12 -> 2012
Run Code Online (Sandbox Code Playgroud)


Jon*_*nyS 1

问题出在 strtotime 上。使用 strtotime("now") 尝试同样的操作。