Php dynamic year

Filed under: Web Development — rasim

dynamicyearIt is pretty easy to insert dynamic year or date in a php page. I don’t understand the developers that hard-code the years, especially on e-commerce websites. I had to redo a few of them. A lot of times it would be a long list of years without even a loop. I’ve seen over 100-line code listing years and it actually take a lot more work to create a list than write a for loop.

These are some of the places where I think years should be dynamic:

1) Dynamic Copyright Year. Do you like updating your copyright in the footer every year? Do you ever forget? Solutions is very simple:

copyright &copy; <?php echo date('Y'); ?>  yoursiteurl.com

2) Date of birth – dynamic year. This will print years of birth from 5 to 100 year old.


//From hundred years ago
$start_year = date('Y')-100;
//To five years ago
$end_year = date('Y')-5;
//loop through the years, low to high.
for ($i=$start_year; $i<=$end_year; $i++) {
//your logic here, for now we'll just echo it out
echo $i."<br/>";
}

3) Credit card expiration, dynamic year. If you don’t do this, you may get a call a few years after finishing up the project. Just kidding, but it sucks to change hard-coded values when customers call and complain that they can’t check out because of the credit card expiration year.

//From current year
$start_year = date('Y');
//To a few years in the future, ten in this case
$end_year = date('Y')+10;
//loop through the years, current to future.
for ($i=$start_year; $i<=$end_year; $i++) {
//your logic here, for now we'll just echo it out
echo $i."<br/>";
}

That’s it. It took me about 5 minutes to write this whole post, including the code. I am pretty sure it takes longer for some developers to copy-paste just the years of birth and even longer to find the place and change it a year later.

Let me know if you need any other dynamic date or year examples. Just thought since it is the end of the year, you may have to change the copyright year in a footer. :)

No Comments »

No comments yet.

Leave a comment