-1

I was wondering if there is a way to update a certain number value, per year?

Similar to how you would update a website date in the footer like this:

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

I'm looking for a way to update a set number each year / month.

Example, say a website says they have been in business for 10 years. Then when the next year passes, I want PHP to automatically update the value to 11 years. Note, that I have to start with the number 10

Another example would be for age: John is 21. After a year passes I want PHP to update the site to say, John is 22.

Or Betty has worked here for 5 months.... After the next month passes it would update to 6, then once it hits 12 months is would change to 1 year then 2 years etc... Thats a little more involved, but you get the idea.

If someone knows how this can be achieved I would appreciate the help, or if you can point me in the right direction to solving this problem that would work too.

daugaard47
  • 1,726
  • 5
  • 39
  • 74

4 Answers4

2

Yes, you need to understand two things - the current date and the date you are comparing it to. You then simply need to compare the too.

I would suggest using the PHP DateTime, DateInterval, etc. classes which greatly simply this for you.

For example:

$now = new DateTime('now');
$comparison_date = new DateTime('2005-01-01'); // roughly 10 years ago
$interval = $now->diff($comparison_date); // returns DateInterval object
$years_difference = $interval->y;
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
1

You can find your answer here: How to calculate the difference between two dates using PHP?

By using strtotime() to convert two dates to unix time and calculate the number of seconds between them then reconvert to human readable.

Community
  • 1
  • 1
0

To calculate the difference between to years you can use a simple sum like this:

<?php

$cur_year = date("Y");
$year = 2008;
$total_years = $cur_year - $year;

echo ($total_years);

?>

For months you could use a similar thing

CalvT
  • 3,123
  • 6
  • 37
  • 54
0

Substract the initial Unix timestamp with the current timestamp (time() returns it), divide by 60 * 60 * 24 * 365, and round accordingly (you will probably want to floor() the years an user has been registered, and ceil() the years a bussiness have been working)

$start = 12345646;
$years = ceil((time() - $start) / 31536000.0); // Important: use a float

Note this uses "year" as a set of 365 days. It won't take into account leap years.