生成日期PHP

时间:2018-02-24 00:54:16

标签: php

我有以下代码,并想知道是否有一个更简单的方法没有所有ifelse条件

if ($year == 13){
    $shyear = '2012 / 2013';
}elseif ($year == 12){
    $shyear = '2011 / 2012';
}elseif ($year == 11){
    $shyear = '2010 / 2011';
}elseif ($year == 10){
    $shyear = '2009 / 2010';
}elseif ($year == 9){
    $shyear = '2008 / 2009';
}elseif ($year == 8){
    $shyear = '2007 / 2008';
}

3 个答案:

答案 0 :(得分:1)

我爱DateTime。干净,简单,快速,可读。

$dt = DateTime::createFromFormat('y', $year);
$shyear = $dt->format('Y')-1 . " / " . $dt->format('Y');

这将导致$shyear成为:

2007 / 2008

让我们测试一下:

$dt = DateTime::createFromFormat('y', '8');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

$dt = DateTime::createFromFormat('y', '9');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

$dt = DateTime::createFromFormat('y', '10');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

$dt = DateTime::createFromFormat('y', '11');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

$dt = DateTime::createFromFormat('y', '12');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

$dt = DateTime::createFromFormat('y', '13');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

结果:

2007 / 2008
2008 / 2009
2009 / 2010
2010 / 2011
2011 / 2012
2012 / 2013

也适用于2000年!

$dt = DateTime::createFromFormat('y', '0');
echo $dt->format('Y')-1 . " / " . $dt->format('Y');

1999 / 2000中的结果。

答案 1 :(得分:0)

$ shyear = strlen($ year)> 1? sprintf('20%d / 20%d',$ year-1,$ year):sprintf('200%d / 200%d',$ year-1,$ year);

<?php
$year = 15;
$shyear = strlen($year) > 1 ? sprintf('20%d / 20%d', $year-1, $year) : sprintf('200%d / 200%d', $year-1, $year);
echo $shyear;
?>

写了这段代码,输出“2014/2015”

答案 2 :(得分:0)

另一种方式,考虑到您只需要特定的年份范围,就可以使用关联数组

$array = array( "7"=>"2007", 
                "8"=>"2008", 
                "9"=>"2008",
                "10"=>"2010",
                "11"=>"2011",
                "12"=>"2012",
                "13"=>"2013");

if ($year >= 8 and $year <= 13) {
      $shyear = $array["".($year-1).""]."/".$array["$year"];
}