Jump to content

Trying to determine length (in months and years) based on todays date


DBookatay

Recommended Posts

I have an online credit app with several fields that are month and year selections (time at address, hire date, etc) and want to not only display the results (March, 2011) that the analyst views, but also the length based on when the app was originally submitted. Unfortunately I can not change the structure of the dB, so instead need to change the output of the php, but have been unsuccessful.

The rows are: "ap_add8" = Month (January - December full text,) "ap_add9" = Year (2014) and "submitted" = the date the ap was submitted (2014-03-24.)

I've tried

$Difference = abs(strtotime($row['ap_add9'].'-'.date("m", mktime(0, 0, 0, $row['ad_add8']))) - strtotime(date("Y").'-'.date(m))); 
$Years = floor($Difference / (365*60*60*24)); 
$Months = floor(($Difference - $Years * 365*60*60*24) / (30*60*60*24)); 
if ($Years !="0") {$Years = $Years.' years, ';} else {$Years = NULL;}
if ($Months !="0") {$Months = $Months.' months';} else {$Months = NULL;} 

to get it working based on todays date, but can't even get that working properly, let alone based on when the app was submitted.

Something like this would work:

<?php

$sampleRow = array(
  'ap_add8' => 'April'
  , 'ap_add9' => '2012'
  , 'submitted' => '2014-3-24'
);


$date = new DateTime($sampleRow['ap_add8'].' 1 '.$sampleRow['ap_add9']);
$now = new DateTime($sampleRow['submitted']);

$diff = $date->diff($now);
echo 'Length: '.$diff->y.' year(s) and '.$diff->m.' month(s) ';

[edit] Bah, DateTime works too. I like doing the math (if you call a couple subtractions "math") manually. [/edit]

 

Turn ap_add8 into a number any way you want: an array of months or strtotime() are the easiest.

 

Then:

Y = end year - start year
M = end month - start month
if M < 0 then
    Y = Y - 1
    M = M + 12
So March 2014 to June 2014 is

Y = 2014 - 2014 = 0
M = 6 - 3 = 3
3 months. June 2014 to March 2015 is

Y = 2015 - 2014 = 1
M = 3 - 6 = -3

Y = Y - 1 = 0
M = -3 + 12 = 9
9 months.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.