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

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


当前回答

随着PHP朝着更面向对象的方向发展,我很惊讶这里没有人引用内置的DateTime类:

$now = new DateTime();
$year = $now->format("Y");

或者在实例化时使用类成员访问的一行程序(php>=5.4):

$year = (new DateTime)->format("Y");

其他回答

这个给出了当地时间:

$year = date('Y'); // 2008

这个UTC:

$year = gmdate('Y'); // 2008

全年使用:

 <?php 
    echo $curr_year = date('Y'); // it will display full year ex. 2017
?>

或者只得到两位年份,就像这样:

 <?php 
    echo $curr_year = date('y'); // it will display short 2 digit year ex. 17
?>

如果你的服务器支持短标签,或者你使用PHP 5.4,你可以使用:

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

要使用PHP的日期函数获取当前年份,你可以像这样传入“Y”格式字符:

//Getting the current year using
//PHP's date function.

$year = date("Y");
echo $year;

上面的例子将打印出当前年份的完整的4位数字表示。

如果你只想检索2位数格式,那么你可以使用小写的“y”格式字符:

$year = date("y");
echo $year;
1
2
$year = date("y");
echo $year;

上面的代码片段将打印20而不是2020年,或者打印19而不是2019年,等等。