Jump to content

Converting a long string of days into (Year, Month, Days) format


envexlabs

Recommended Posts

Hey,

 

I have a function that converts 2 dates into a string of days inbetween those two dates.

 

So if the string is returned as 124512 days, how would i go about figuring out how many years/months/days that is?

 

Any ideas of where to even start?

 

Thanks,

 

envex

UPDATE

 

I think i've figured it out, any critique on my code? Tear it apart please!

 

function days_between($day){

$daysin = array(31,28,31,30,31,30,31,31,30,31,30,31);

$years = $day / 365;
$years = floor($years);

$removedays = $years * 365;
$days = $day - $removedays;

if($days <= 31){
	$days = $days;
	$months = 0;
}else{

	for($i = 1; $i <= 12; $i++){

		if($days >= 0){

			$days = $days - $daysin[$i];
			$months = $months + 1;

		}

	}

	$days = $days + $daysin[$months];	
}

$days = $days != 0 ? "$days days" : '';
$months = $months != 0 ? "$months months, " : '';
$years = $years != 0 ? "$years years, " : '';

$time =  $years.$months.$days;

return $time;

}

couple errors

<?php function days_between($day){

$daysin = array(31,28,31,30,31,30,31,31,30,31,30,31);

$years = $day / 365;
$years = floor($years);

$removedays = $years * 365;
$days = $day - $removedays;

if($days <= 31){
	$days = $days;
	$months = 0;
}else{

	for($i = 1; $i <= 12; $i++){

		if($days >= $daysin[$i]){ //make sure its more than current month so you dont get negative days

			$days = $days - $daysin[$i];
			$months = $months + 1;

		}
else break;

	}

	//$days = $days + $daysin[$months];	
}

$days = $days != 0 ? "$days days" : '';
$months = $months != 0 ? "$months months, " : '';
$years = $years != 0 ? "$years years, " : '';

$time =  $years.$months.$days;

return $time;

}?>

 

think that looks better.

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.