Advertisement
Advertisement


How do I use PHP to get the current year?


Question

I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be out-of-date. How would I make the year update automatically with PHP 4 and PHP 5?

2014/04/15
1
951
4/15/2014 12:02:57 PM

Accepted Answer

You can use either date or strftime. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)

For example:

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

On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.

2014/02/20
1176
2/20/2014 7:02:05 PM


My super lazy version of showing a copyright line, that automatically stays updated:

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

This year (2008), it will say:

© 2008 Me, Inc.

Next year, it will say:

© 2008-2009 Me, Inc.

and forever stay updated with the current year.


Or (PHP 5.3.0+) a compact way to do it using an anonymous function so you don't have variables leaking out and don't repeat code/constants:

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

With PHP heading in a more object-oriented direction, I'm surprised nobody here has referenced the built-in DateTime class:

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

or one-liner with class member access on instantiation (php>=5.4):

$year = (new DateTime)->format("Y");
2013/08/20

http://us2.php.net/date

echo date('Y');
2012/05/24

strftime("%Y");

I love strftime. It's a great function for grabbing/recombining chunks of dates/times.

Plus it respects locale settings which the date function doesn't do.

2008/09/15

This one gives you the local time:

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

And this one UTC:

$year = gmdate('Y'); // 2008
2016/01/17

Source: https://stackoverflow.com/questions/64003
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]