0

I have a line of text as follows...

"Now married for XXX years, my wife and I are excited for the future."

Our wedding date is: June 7th, 2008

So, currently it reads:

"Now married for two years, my wife and I are excited for the future."

What php code can I put in the XXX space to automatically insert the number of years we have been married?

4 Answers4

1
<?php
$married = new DateTime('2009-10-11');
$currentdate = new DateTime();
$interval = $married->diff($currentdate);
echo $interval->format('%y years');
?>

Something along those lines should do the trick. I haven't run this code, so you may need to tweak it a bit but it should get you started.

Cody
  • 3,734
  • 2
  • 24
  • 29
0

What you can do is subtract the current date and the anniversary date. use a function like one that is displayed here:

http://www.ozzu.com/programming-forum/subtracting-date-from-another-t29111.html

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • 2
    He wants something that calculates years married. To ensure that there was no divorce and subsequent re-marriage it would need hooks into the the state's and church's registries. – Bernd Elkemann Mar 11 '11 at 20:35
  • And then there's the other wives as well, can't forget to include those in the calculations. – Marc B Mar 11 '11 at 20:36
0
<?
$anniv = new DateTime('June 7th, 2008');
$now = new DateTime();
$interval = $now->diff($anniv, true);
echo 'Now married '.$interval->y.' years';
?>
DeaconDesperado
  • 9,977
  • 9
  • 47
  • 77
0

The DateTime objects that people have used so far only work if you have a newer version of PHP. Here's a solution without them. Finding just the number of years is pretty easy.

<?php
$date1 = strtotime("June 7th, 2008");  //Get general timestamp for day
$today = time(); //Today's date

$secs = $today - $date1;  //Get number of seconds passed since $date1 til $today
$years = floor($secs / (60*60*24*365)) //Derive years from seconds using number of seconds in a year

echo $years;
?>

or, in a single line of code:

<?php
$years = floor((time() - strtotime("June 7th, 2008")) / (60 * 60 * 24 * 365));
?>
Phoenix
  • 4,488
  • 1
  • 21
  • 13