我想在一个网站的页脚放一个版权声明,但我认为这对于过时的年份来说是非常俗气的。

如何在php4或php5中自动更新年份?


当前回答

在date函数的第二个参数中可以得到更多的值 Strtotime返回参数传递的时间戳

// This work when you get time as string
echo date('Y', strtotime("now"));

// Get next years
echo date('Y', strtotime("+1 years"));

// 
echo strftime("%Y", strtotime("now"));

使用datetime类

echo (new DateTime)->format('Y');

其他回答

在date函数的第二个参数中可以得到更多的值 Strtotime返回参数传递的时间戳

// This work when you get time as string
echo date('Y', strtotime("now"));

// Get next years
echo date('Y', strtotime("+1 years"));

// 
echo strftime("%Y", strtotime("now"));

使用datetime类

echo (new DateTime)->format('Y');

创建一个helper函数并调用它

getCurrentYear();

function getCurrentYear(){
    return now()->year;
}

只写:

date("Y") // A full numeric representation of a year, 4 digits
          // Examples: 1999 or 2003

Or:

date("y"); // A two digit representation of a year     Examples: 99 or 03

然后“echo”这个值…

使用PHP date()函数。

格式是Y,大写的Y是四位数的年份。

<?php echo date("Y"); ?>

我的超级懒惰版本显示版权行,自动保持更新:

&copy; <?php 
$copyYear = 2008; 
$curYear = date('Y'); 
echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');
?> Me, Inc.

今年(2008年),它会说:

©2008 Me, Inc

明年,它会说:

©2008-2009 Me, Inc

并且永远保持当前年份的更新。


或者(PHP 5.3.0+)一种使用匿名函数的紧凑方法,这样你就不会有变量泄露,也不会重复代码/常量:

&copy; 
<?php call_user_func(function($y){$c=date('Y');echo $y.(($y!=$c)?'-'.$c:'');}, 2008); ?> 
Me, Inc.